



from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PretrainedConfig, PreTrainedTokenizer
from ...onnx import OnnxConfig, PatchingSpec
from ...utils import TensorType, is_torch_available, logging


_lowerCamelCase         =	logging.get_logger(__name__)

_lowerCamelCase         =	{
    """microsoft/layoutlm-base-uncased""": (
        """https://huggingface.co/microsoft/layoutlm-base-uncased/resolve/main/config.json"""
    ),
    """microsoft/layoutlm-large-uncased""": (
        """https://huggingface.co/microsoft/layoutlm-large-uncased/resolve/main/config.json"""
    ),
}

class    _SCREAMING_SNAKE_CASE						(UpperCamelCase			):
     lowerCAmelCase       =      """layoutlm"""





     def __init__(							self			:				int  ,	UpperCamelCase			:				Optional[Any]=3_0_5_2_2  ,	UpperCamelCase			:				str=7_6_8  ,	UpperCamelCase			:				str=1_2  ,	UpperCamelCase			:				Optional[Any]=1_2  ,	UpperCamelCase			:				Dict=3_0_7_2  ,	UpperCamelCase			:				Tuple="gelu"  ,	UpperCamelCase			:				int=0.1  ,	UpperCamelCase			:				Union[str, Any]=0.1  ,	UpperCamelCase			:				List[Any]=5_1_2  ,	UpperCamelCase			:				List[str]=2  ,	UpperCamelCase			:				Optional[Any]=0.0_2  ,	UpperCamelCase			:				int=1E-12  ,	UpperCamelCase			:				str=0  ,	UpperCamelCase			:				Optional[int]="absolute"  ,	UpperCamelCase			:				int=True  ,	UpperCamelCase			:				List[Any]=1_0_2_4  ,	**UpperCamelCase			:				Dict  ,	)->int:
      super().__init__(pad_token_id=UpperCamelCase  ,	**UpperCamelCase					)
      __SCREAMING_SNAKE_CASE							:     Union[str, Any]							=						vocab_size
      __SCREAMING_SNAKE_CASE							:     Any							=						hidden_size
      __SCREAMING_SNAKE_CASE							:     Optional[int]							=						num_hidden_layers
      __SCREAMING_SNAKE_CASE							:     str							=						num_attention_heads
      __SCREAMING_SNAKE_CASE							:     int							=						hidden_act
      __SCREAMING_SNAKE_CASE							:     Any							=						intermediate_size
      __SCREAMING_SNAKE_CASE							:     List[str]							=						hidden_dropout_prob
      __SCREAMING_SNAKE_CASE							:     Union[str, Any]							=						attention_probs_dropout_prob
      __SCREAMING_SNAKE_CASE							:     Tuple							=						max_position_embeddings
      __SCREAMING_SNAKE_CASE							:     Optional[Any]							=						type_vocab_size
      __SCREAMING_SNAKE_CASE							:     Optional[Any]							=						initializer_range
      __SCREAMING_SNAKE_CASE							:     List[str]							=						layer_norm_eps
      __SCREAMING_SNAKE_CASE							:     int							=						position_embedding_type
      __SCREAMING_SNAKE_CASE							:     Union[str, Any]							=						use_cache
      __SCREAMING_SNAKE_CASE							:     Dict							=						max_ad_position_embeddings






class    _SCREAMING_SNAKE_CASE						(UpperCamelCase			):





     def __init__(							self			:				str  ,	UpperCamelCase			:				PretrainedConfig  ,	UpperCamelCase			:				str = "default"  ,	UpperCamelCase			:				List[PatchingSpec] = None  ,	)->Optional[int]:
      super().__init__(UpperCamelCase  ,	task=UpperCamelCase  ,	patching_specs=UpperCamelCase					)
      __SCREAMING_SNAKE_CASE							:     Optional[int]							=						config.max_ad_position_embeddings - 1





     @property
     def 						__snake_case     (							self			:				Union[str, Any]					)->Mapping[str, Mapping[int, str]]:
      return OrderedDict(
          [
              ("input_ids", {0: "batch", 1: "sequence"}),
              ("bbox", {0: "batch", 1: "sequence"}),
              ("attention_mask", {0: "batch", 1: "sequence"}),
              ("token_type_ids", {0: "batch", 1: "sequence"}),
          ]					)






     def 						__snake_case     (							self			:				Tuple  ,	UpperCamelCase			:				PreTrainedTokenizer  ,	UpperCamelCase			:				int = -1  ,	UpperCamelCase			:				int = -1  ,	UpperCamelCase			:				bool = False  ,	UpperCamelCase			:				Optional[TensorType] = None  ,	)->Mapping[str, Any]:
      __SCREAMING_SNAKE_CASE							:     Optional[int]							=						super().generate_dummy_inputs(
          UpperCamelCase  ,	batch_size=UpperCamelCase  ,	seq_length=UpperCamelCase  ,	is_pair=UpperCamelCase  ,	framework=UpperCamelCase					)

      # Generate a dummy bbox
      __SCREAMING_SNAKE_CASE							:     List[str]							=						[4_8, 8_4, 7_3, 1_2_8]

      if not framework == TensorType.PYTORCH:
       raise NotImplementedError("Exporting LayoutLM to ONNX is currently only supported for PyTorch."					)

      if not is_torch_available():
       raise ValueError("Cannot generate dummy inputs without PyTorch installed."					)
      import torch

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE							:     str							=						input_dict["input_ids"].shape
      __SCREAMING_SNAKE_CASE							:     List[Any]							=						torch.tensor([*[box] * seq_length]					).tile(UpperCamelCase  ,	1  ,	1					)
      return input_dict










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  A_ (			a_  ):







 """simple docstring"""





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

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




class  A_ :







 """simple docstring"""





 _UpperCamelCase					:			str     	=       '''\u001b[1m'''
 _UpperCamelCase					:			Optional[Any]     	=       '''\u001b[31m'''
 _UpperCamelCase					:			List[Any]     	=       '''\u001b[90m'''
 _UpperCamelCase					:			Tuple     	=       '''\u001b[0m'''
 @classmethod
 def 	_UpperCamelCase     (      cls       :			Any							,     _a       :			Tuple					)     ->      Any:
      return f'{cls._bold}{s}{cls._reset}'
 @classmethod
 def 	_UpperCamelCase     (      cls       :			Optional[Any]							,     _a       :			List[Any]					)     ->      str:
      return f'{cls._bold}{cls._red}{s}{cls._reset}'

 @classmethod
 def 	_UpperCamelCase     (      cls       :			str							,     _a       :			Optional[Any]					)     ->      Tuple:
      return f'{cls._gray}{s}{cls._reset}'







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




class  A_ :







 """simple docstring"""





 def __init__(      self       :			List[str]							,     _a       :			str					)     ->      str:
      UpperCAmelCase    :					str			=      args




class  A_ (			a_  ):







 """simple docstring"""





 def 	_UpperCamelCase     (      self       :			Optional[int]					)     ->      Any:
      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  A_ (			a_  ):







 """simple docstring"""





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




class  A_ (			a_  ):







 """simple docstring"""





 def 	_UpperCamelCase     (      self       :			List[Any]					)     ->      int:
      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  A_ (			a_  ):







 """simple docstring"""





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

      UpperCAmelCase	,			UpperCAmelCase    :					Tuple			=      whoami(_a					)
      UpperCAmelCase    :					Union[str, Any]			=      self.args.organization if self.args.organization is not None else user
      UpperCAmelCase    :					Dict			=      f'{namespace}/{self.args.name}'
      print(f'You are about to create {ANSI.bold(_a					)}'					)

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



