





'''simple docstring'''






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 				UpperCAmelCase  (    snake_case_     ):




      @staticmethod
      def        lowercase__					(    __snake_case    :				ArgumentParser						)       ->   List[str]:
            _lowerCAmelCase							  =							parser.add_parser("""login"""    ,    help="""Log in using the same credentials as on huggingface.co"""						)
            login_parser.set_defaults(func=lambda __snake_case						: LoginCommand(__snake_case						)						)
            _lowerCAmelCase							  =							parser.add_parser("""whoami"""    ,    help="""Find out which huggingface.co account you are logged in as."""						)
            whoami_parser.set_defaults(func=lambda __snake_case						: WhoamiCommand(__snake_case						)						)
            _lowerCAmelCase							  =							parser.add_parser("""logout"""    ,    help="""Log out"""						)
            logout_parser.set_defaults(func=lambda __snake_case						: LogoutCommand(__snake_case						)						)

            # new system: git-based repo system
            _lowerCAmelCase							  =							parser.add_parser(
                """repo"""    ,    help="""Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos."""    ,    )
            _lowerCAmelCase							  =							repo_parser.add_subparsers(
                help="""Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands"""						)
            _lowerCAmelCase							  =							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=__snake_case    ,    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=__snake_case    ,    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 __snake_case						: RepoCreateCommand(__snake_case						)						)




class 				UpperCAmelCase  :
      _lowercase:    List[Any]		  =     '''\u001b[1m'''
      _lowercase:    List[str]		  =     '''\u001b[31m'''
      _lowercase:    Dict		  =     '''\u001b[90m'''
      _lowercase:    str		  =     '''\u001b[0m'''




      @classmethod
      def        lowercase__					(    cls    :				List[Any]    ,    __snake_case    :				Union[str, Any]						)       ->   int:
            return f"{cls._bold}{s}{cls._reset}"




      @classmethod
      def        lowercase__					(    cls    :				Dict    ,    __snake_case    :				str						)       ->   str:
            return f"{cls._bold}{cls._red}{s}{cls._reset}"




      @classmethod
      def        lowercase__					(    cls    :				Optional[Any]    ,    __snake_case    :				List[Any]						)       ->   Tuple:
            return f"{cls._gray}{s}{cls._reset}"




def      UpperCamelCase__   (	lowerCAmelCase							,			lowerCAmelCase						):





      """simple docstring"""


      _lowerCAmelCase							  =							[max(len(str(lowerCAmelCase						)						) for x in col						) for col in zip(*lowerCAmelCase							,			lowerCAmelCase						)]
      _lowerCAmelCase							  =							("""{{:{}}} """ * len(lowerCAmelCase						)).format(*lowerCAmelCase						)
      _lowerCAmelCase							  =							[]
      lines.append(row_format.format(*lowerCAmelCase						)						)
      lines.append(row_format.format(*["""-""" * w for w in col_widths]						)						)
      for row in rows:
            lines.append(row_format.format(*lowerCAmelCase						)						)
      return "\n".join(lowerCAmelCase						)




class 				UpperCAmelCase  :




      def __init__(    self    :				Any    ,    __snake_case    :				int						)       ->   Optional[Any]:
            _lowerCAmelCase							  =							args




class 				UpperCAmelCase  (    snake_case_     ):




      def        lowercase__					(    self    :				Dict						)       ->   int:
            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 				UpperCAmelCase  (    snake_case_     ):




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




class 				UpperCAmelCase  (    snake_case_     ):




      def        lowercase__					(    self    :				Dict						)       ->   List[Any]:
            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 				UpperCAmelCase  (    snake_case_     ):




      def        lowercase__					(    self    :				str						)       ->   Tuple:
            print(
                ANSI.red(
                    """WARNING! Managing repositories through transformers-cli is deprecated. """
                    """Please use `huggingface-cli` instead."""						)						)
            _lowerCAmelCase							  =							HfFolder.get_token()
            if token is None:
                  print("""Not logged in"""						)
                  exit(1						)
            try:
                  _lowerCAmelCase							  =							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:
                  _lowerCAmelCase							  =							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(""""""						)

            _lowerCAmelCase  ,							_lowerCAmelCase							  =							whoami(__snake_case						)
            _lowerCAmelCase							  =							self.args.organization if self.args.organization is not None else user
            _lowerCAmelCase							  =							f"{namespace}/{self.args.name}"
            print(f"You are about to create {ANSI.bold(__snake_case						)}"						)

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













'''simple docstring'''






import unittest

import numpy as np

from transformers import ElectraConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
      from transformers.models.electra.modeling_flax_electra import (
          FlaxElectraForCausalLM,
          FlaxElectraForMaskedLM,
          FlaxElectraForMultipleChoice,
          FlaxElectraForPreTraining,
          FlaxElectraForQuestionAnswering,
          FlaxElectraForSequenceClassification,
          FlaxElectraForTokenClassification,
          FlaxElectraModel,
      )




class 				UpperCAmelCase  (    unittest.TestCase     ):




      def __init__(    self    :				str    ,    __snake_case    :				str    ,    __snake_case    :				str=13    ,    __snake_case    :				Optional[Any]=7    ,    __snake_case    :				str=True    ,    __snake_case    :				Any=True    ,    __snake_case    :				List[str]=True    ,    __snake_case    :				Any=True    ,    __snake_case    :				List[str]=99    ,    __snake_case    :				Dict=24    ,    __snake_case    :				Any=32    ,    __snake_case    :				List[str]=5    ,    __snake_case    :				Any=4    ,    __snake_case    :				Optional[Any]=37    ,    __snake_case    :				Union[str, Any]="gelu"    ,    __snake_case    :				Dict=0.1    ,    __snake_case    :				int=0.1    ,    __snake_case    :				Dict=5_12    ,    __snake_case    :				List[Any]=16    ,    __snake_case    :				Dict=2    ,    __snake_case    :				str=0.02    ,    __snake_case    :				Any=4    ,    )       ->   Union[str, Any]:
            _lowerCAmelCase							  =							parent
            _lowerCAmelCase							  =							batch_size
            _lowerCAmelCase							  =							seq_length
            _lowerCAmelCase							  =							is_training
            _lowerCAmelCase							  =							use_attention_mask
            _lowerCAmelCase							  =							use_token_type_ids
            _lowerCAmelCase							  =							use_labels
            _lowerCAmelCase							  =							vocab_size
            _lowerCAmelCase							  =							hidden_size
            _lowerCAmelCase							  =							embedding_size
            _lowerCAmelCase							  =							num_hidden_layers
            _lowerCAmelCase							  =							num_attention_heads
            _lowerCAmelCase							  =							intermediate_size
            _lowerCAmelCase							  =							hidden_act
            _lowerCAmelCase							  =							hidden_dropout_prob
            _lowerCAmelCase							  =							attention_probs_dropout_prob
            _lowerCAmelCase							  =							max_position_embeddings
            _lowerCAmelCase							  =							type_vocab_size
            _lowerCAmelCase							  =							type_sequence_label_size
            _lowerCAmelCase							  =							initializer_range
            _lowerCAmelCase							  =							num_choices




      def        lowercase__					(    self    :				Optional[Any]						)       ->   Optional[Any]:
            _lowerCAmelCase							  =							ids_tensor([self.batch_size, self.seq_length]    ,    self.vocab_size						)

            _lowerCAmelCase							  =							None
            if self.use_attention_mask:
                  _lowerCAmelCase							  =							random_attention_mask([self.batch_size, self.seq_length]						)

            _lowerCAmelCase							  =							None
            if self.use_token_type_ids:
                  _lowerCAmelCase							  =							ids_tensor([self.batch_size, self.seq_length]    ,    self.type_vocab_size						)

            _lowerCAmelCase							  =							ElectraConfig(
                vocab_size=self.vocab_size    ,    hidden_size=self.hidden_size    ,    embedding_size=self.embedding_size    ,    num_hidden_layers=self.num_hidden_layers    ,    num_attention_heads=self.num_attention_heads    ,    intermediate_size=self.intermediate_size    ,    hidden_act=self.hidden_act    ,    hidden_dropout_prob=self.hidden_dropout_prob    ,    attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,    max_position_embeddings=self.max_position_embeddings    ,    type_vocab_size=self.type_vocab_size    ,    initializer_range=self.initializer_range    ,    )

            return config, input_ids, token_type_ids, attention_mask




      def        lowercase__					(    self    :				Any						)       ->   Optional[int]:
            _lowerCAmelCase							  =							self.prepare_config_and_inputs()
            _lowerCAmelCase  ,							_lowerCAmelCase  ,							_lowerCAmelCase  ,							_lowerCAmelCase							  =							config_and_inputs
            _lowerCAmelCase							  =							{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask}
            return config, inputs_dict




@require_flax
class 				UpperCAmelCase  (    snake_case_							,	unittest.TestCase     ):
      _lowercase:    str		  =     True

      _lowercase:    Optional[Any]		  =     (
          (
              FlaxElectraModel,
              FlaxElectraForCausalLM,
              FlaxElectraForMaskedLM,
              FlaxElectraForPreTraining,
              FlaxElectraForTokenClassification,
              FlaxElectraForQuestionAnswering,
              FlaxElectraForMultipleChoice,
              FlaxElectraForSequenceClassification,
          )
          if is_flax_available()
          else ()
      )




      def        lowercase__					(    self    :				Tuple						)       ->   Optional[int]:
            _lowerCAmelCase							  =							FlaxElectraModelTester(self						)




      @slow
      def        lowercase__					(    self    :				List[Any]						)       ->   str:
            for model_class_name in self.all_model_classes:
                  if model_class_name == FlaxElectraForMaskedLM:
                        _lowerCAmelCase							  =							model_class_name.from_pretrained("""google/electra-small-generator"""						)
                  else:
                        _lowerCAmelCase							  =							model_class_name.from_pretrained("""google/electra-small-discriminator"""						)
                  _lowerCAmelCase							  =							model(np.ones((1, 1)						)						)
                  self.assertIsNotNone(__snake_case						)






