

"""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        __lowercase     (      __lowerCamelCase   ):

  @staticmethod
  def 				__lowercase    (					A						:     ArgumentParser      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Tuple   				=   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__   :					Any   				=   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__   :					Union[str, 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[Any]   				=   parser.add_parser(
       """repo"""   ,help="""Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos."""   ,)
   UpperCAmelCase__   :					List[Any]   				=   repo_parser.add_subparsers(
       help="""Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands"""      )
   UpperCAmelCase__   :					Tuple   				=   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        __lowercase     :
  snake_case_			    =    """\u001b[1m"""
  snake_case_			    =    """\u001b[31m"""
  snake_case_			    =    """\u001b[90m"""
  snake_case_			    =    """\u001b[0m"""

  @classmethod
  def 				__lowercase    (					cls						:     Tuple   ,A						:     Optional[int]      ):






   '''simple docstring'''
   return f"{cls._bold}{s}{cls._reset}"

  @classmethod
  def 				__lowercase    (					cls						:     Dict   ,A						:     List[Any]      ):






   '''simple docstring'''
   return f"{cls._bold}{cls._red}{s}{cls._reset}"




  @classmethod
  def 				__lowercase    (					cls						:     Dict   ,A						:     Union[str, Any]      ):






   '''simple docstring'''
   return f"{cls._gray}{s}{cls._reset}"







def 					lowerCAmelCase  (   __UpperCamelCase							,      __UpperCamelCase ):
 '''simple docstring'''





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







class        __lowercase     :

  def __init__(					self						:     Tuple   ,A						:     Tuple      ):






   '''simple docstring'''
   UpperCAmelCase__   :					List[str]   				=   args







class        __lowercase     (      __lowerCamelCase   ):

  def 				__lowercase    (					self						:     int      ):






   '''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        __lowercase     (      __lowerCamelCase   ):

  def 				__lowercase    (					self						:     List[Any]      ):






   '''simple docstring'''
   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__   :					Dict   				=   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        __lowercase     (      __lowerCamelCase   ):

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






   '''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        __lowercase     (      __lowerCamelCase   ):

  def 				__lowercase    (					self						:     Optional[int]      ):






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

   UpperCAmelCase__   :					List[str]   				=   whoami(A      )
   UpperCAmelCase__   :					Dict   				=   self.args.organization if self.args.organization is not None else user
   UpperCAmelCase__   :					Tuple   				=   f"{namespace}/{self.args.name}"
   print(f"You are about to create {ANSI.bold(A      )}"      )

   if not self.args.yes:
    UpperCAmelCase__   :					Union[str, 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(""""""      )








"""simple docstring"""




import json
from typing import TYPE_CHECKING, List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_deberta import DebertaTokenizer


if TYPE_CHECKING:
      from transformers.pipelines.conversational import Conversation


__UpperCAmelCase	=			logging.get_logger(__name__)

__UpperCAmelCase	=			{'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}

__UpperCAmelCase	=			{
    'vocab_file': {
        'microsoft/deberta-base': 'https://huggingface.co/microsoft/deberta-base/resolve/main/vocab.json',
        'microsoft/deberta-large': 'https://huggingface.co/microsoft/deberta-large/resolve/main/vocab.json',
        'microsoft/deberta-xlarge': 'https://huggingface.co/microsoft/deberta-xlarge/resolve/main/vocab.json',
        'microsoft/deberta-base-mnli': 'https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/vocab.json',
        'microsoft/deberta-large-mnli': 'https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/vocab.json',
        'microsoft/deberta-xlarge-mnli': (
            'https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/vocab.json'
        ),
    },
    'merges_file': {
        'microsoft/deberta-base': 'https://huggingface.co/microsoft/deberta-base/resolve/main/merges.txt',
        'microsoft/deberta-large': 'https://huggingface.co/microsoft/deberta-large/resolve/main/merges.txt',
        'microsoft/deberta-xlarge': 'https://huggingface.co/microsoft/deberta-xlarge/resolve/main/merges.txt',
        'microsoft/deberta-base-mnli': 'https://huggingface.co/microsoft/deberta-base-mnli/resolve/main/merges.txt',
        'microsoft/deberta-large-mnli': 'https://huggingface.co/microsoft/deberta-large-mnli/resolve/main/merges.txt',
        'microsoft/deberta-xlarge-mnli': (
            'https://huggingface.co/microsoft/deberta-xlarge-mnli/resolve/main/merges.txt'
        ),
    },
}

__UpperCAmelCase	=			{
    'microsoft/deberta-base': 512,
    'microsoft/deberta-large': 512,
    'microsoft/deberta-xlarge': 512,
    'microsoft/deberta-base-mnli': 512,
    'microsoft/deberta-large-mnli': 512,
    'microsoft/deberta-xlarge-mnli': 512,
}

__UpperCAmelCase	=			{
    'microsoft/deberta-base': {'do_lower_case': False},
    'microsoft/deberta-large': {'do_lower_case': False},
}







class        __lowercase     (      __lowerCamelCase   ):
  snake_case_			    =    VOCAB_FILES_NAMES
  snake_case_			    =    PRETRAINED_VOCAB_FILES_MAP
  snake_case_			    =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  snake_case_			    =    ["""input_ids""", """attention_mask""", """token_type_ids"""]
  snake_case_			    =    DebertaTokenizer

  def __init__(					self						:     Optional[Any]   ,A						:     Any=None   ,A						:     Any=None   ,A						:     Dict=None   ,A						:     Optional[int]="replace"   ,A						:     Optional[int]="[CLS]"   ,A						:     str="[SEP]"   ,A						:     Optional[int]="[SEP]"   ,A						:     List[Any]="[CLS]"   ,A						:     Dict="[UNK]"   ,A						:     List[str]="[PAD]"   ,A						:     Optional[Any]="[MASK]"   ,A						:     str=False   ,**A						:     Dict   ,):






   '''simple docstring'''
   super().__init__(
       A   ,A   ,tokenizer_file=A   ,errors=A   ,bos_token=A   ,eos_token=A   ,unk_token=A   ,sep_token=A   ,cls_token=A   ,pad_token=A   ,mask_token=A   ,add_prefix_space=A   ,**A   ,)
   UpperCAmelCase__   :					Tuple   				=   kwargs.pop("""add_bos_token"""   ,A      )

   UpperCAmelCase__   :					Tuple   				=   json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()      )
   if pre_tok_state.get("""add_prefix_space"""   ,A      ) != add_prefix_space:
    UpperCAmelCase__   :					List[Any]   				=   getattr(A   ,pre_tok_state.pop("""type"""      )      )
    UpperCAmelCase__   :					Any   				=   add_prefix_space
    UpperCAmelCase__   :					List[Any]   				=   pre_tok_class(**A      )

   UpperCAmelCase__   :					str   				=   add_prefix_space

  @property
  def 				__lowercase    (					self						:     str      ):






   '''simple docstring'''
   if self._mask_token is None:
    if self.verbose:
     logger.error("""Using mask_token, but it is not set yet."""      )
    return None
   return str(self._mask_token      )

  @mask_token.setter
  def 				__lowercase    (					self						:     Dict   ,A						:     str      ):






   '''simple docstring'''
   UpperCAmelCase__   :					str   				=   AddedToken(A   ,lstrip=A   ,rstrip=A      ) if isinstance(A   ,A      ) else value
   UpperCAmelCase__   :					List[str]   				=   value

  def 				__lowercase    (					self						:     Tuple   ,A						:     List[int]   ,A						:     Optional[List[int]] = None      ):






   '''simple docstring'''
   if token_ids_a is None:
    return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
   UpperCAmelCase__   :					Dict   				=   [self.cls_token_id]
   UpperCAmelCase__   :					str   				=   [self.sep_token_id]
   return cls + token_ids_a + sep + token_ids_a + sep

  def 				__lowercase    (					self						:     Tuple   ,A						:     List[int]   ,A						:     Optional[List[int]] = None      ):






   '''simple docstring'''
   UpperCAmelCase__   :					List[str]   				=   [self.sep_token_id]
   UpperCAmelCase__   :					str   				=   [self.cls_token_id]

   if token_ids_a is None:
    return len(cls + token_ids_a + sep      ) * [0]
   return len(cls + token_ids_a + sep      ) * [0] + len(token_ids_a + sep      ) * [1]

  def 				__lowercase    (					self						:     int   ,*A						:     Tuple   ,**A						:     Optional[int]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					int   				=   kwargs.get("""is_split_into_words"""   ,A      )
   assert self.add_prefix_space or not is_split_into_words, (
       f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
       "to use it with pretokenized inputs."
   )

   return super()._batch_encode_plus(*A   ,**A      )

  def 				__lowercase    (					self						:     str   ,*A						:     List[str]   ,**A						:     str      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Optional[int]   				=   kwargs.get("""is_split_into_words"""   ,A      )

   assert self.add_prefix_space or not is_split_into_words, (
       f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
       "to use it with pretokenized inputs."
   )

   return super()._encode_plus(*A   ,**A      )

  def 				__lowercase    (					self						:     Tuple   ,A						:     str   ,A						:     Optional[str] = None      ):






   '''simple docstring'''
   UpperCAmelCase__   :					int   				=   self._tokenizer.model.save(A   ,name=A      )
   return tuple(A      )




  def 				__lowercase    (					self						:     List[str]   ,A						:     "Conversation"      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Dict   				=   []
   for is_user, text in conversation.iter_texts():
    input_ids.extend(self.encode(A   ,add_special_tokens=A      ) + [self.eos_token_id]      )

   if len(A      ) > self.model_max_length:
    UpperCAmelCase__   :					Optional[int]   				=   input_ids[-self.model_max_length :]
   return input_ids





