





import os
from typing import List, Union

import tensorflow as tf
from tensorflow_text import BertTokenizer as BertTokenizerLayer
from tensorflow_text import FastBertTokenizer, ShrinkLongestTrimmer, case_fold_utfa, combine_segments, pad_model_inputs

from .tokenization_bert import BertTokenizer

class   __snake_case	(			tf.keras.layers.Layer   ):






    '''simple docstring'''





    def __init__(   self						:		Any			,						snake_case						:		List			,						snake_case						:		bool			,						snake_case						:		int = None			,						snake_case						:		int = None			,						snake_case						:		int = None			,						snake_case						:		str = "longest"			,						snake_case						:		bool = True			,						snake_case						:		int = 512			,						snake_case						:		int = None			,						snake_case						:		bool = True			,						snake_case						:		bool = True			,						snake_case						:		bool = True			,						**snake_case						:		Optional[Any]			,						):

      """simple docstring"""





      super().__init__()
      if use_fast_bert_tokenizer:
        __lowerCAmelCase			=				FastBertTokenizer(
            lowerCAmelCase_			,						token_out_type=tf.intaa			,						lower_case_nfd_strip_accents=lowerCAmelCase_			,						**lowerCAmelCase_							)
      else:
        __lowerCAmelCase			=				tf.lookup.StaticVocabularyTable(
            tf.lookup.KeyValueTensorInitializer(
                keys=lowerCAmelCase_			,						key_dtype=tf.string			,						values=tf.range(tf.size(lowerCAmelCase_			,						out_type=tf.intaa							)			,						dtype=tf.intaa							)			,						value_dtype=tf.intaa			,						)			,						num_oov_buckets=1			,						)
        __lowerCAmelCase			=				BertTokenizerLayer(
            lowerCAmelCase_			,						token_out_type=tf.intaa			,						lower_case=lowerCAmelCase_			,						**lowerCAmelCase_							)

      __lowerCAmelCase			=				vocab_list
      __lowerCAmelCase			=				do_lower_case
      __lowerCAmelCase			=				cls_token_id or vocab_list.index('''[CLS]'''							)
      __lowerCAmelCase			=				sep_token_id or vocab_list.index('''[SEP]'''							)
      __lowerCAmelCase			=				pad_token_id or vocab_list.index('''[PAD]'''							)
      __lowerCAmelCase			=				ShrinkLongestTrimmer(max_length - 3			,						axis=1							)  # Allow room for special tokens
      __lowerCAmelCase			=				max_length
      __lowerCAmelCase			=				padding
      __lowerCAmelCase			=				truncation
      __lowerCAmelCase			=				pad_to_multiple_of
      __lowerCAmelCase			=				return_token_type_ids
      __lowerCAmelCase			=				return_attention_mask





    @classmethod
    def 	A		(   cls						:		Dict			,						snake_case						:		"PreTrainedTokenizerBase"			,						**snake_case						:		List[Any]							):  # noqa: F821

      """simple docstring"""





      __lowerCAmelCase			=				kwargs.pop('''do_lower_case'''			,						lowerCAmelCase_							)
      __lowerCAmelCase			=				tokenizer.do_lower_case if do_lower_case is None else do_lower_case
      __lowerCAmelCase			=				kwargs.pop('''cls_token_id'''			,						lowerCAmelCase_							)
      __lowerCAmelCase			=				tokenizer.cls_token_id if cls_token_id is None else cls_token_id
      __lowerCAmelCase			=				kwargs.pop('''sep_token_id'''			,						lowerCAmelCase_							)
      __lowerCAmelCase			=				tokenizer.sep_token_id if sep_token_id is None else sep_token_id
      __lowerCAmelCase			=				kwargs.pop('''pad_token_id'''			,						lowerCAmelCase_							)
      __lowerCAmelCase			=				tokenizer.pad_token_id if pad_token_id is None else pad_token_id

      __lowerCAmelCase			=				tokenizer.get_vocab()
      __lowerCAmelCase			=				sorted([(wordpiece, idx) for wordpiece, idx in vocab.items()]			,						key=lambda snake_case							: x[1]							)
      __lowerCAmelCase			=				[entry[0] for entry in vocab]
      return cls(
          vocab_list=lowerCAmelCase_			,						do_lower_case=lowerCAmelCase_			,						cls_token_id=lowerCAmelCase_			,						sep_token_id=lowerCAmelCase_			,						pad_token_id=lowerCAmelCase_			,						**lowerCAmelCase_			,						)





    @classmethod
    def 	A		(   cls						:		Optional[int]			,						snake_case						:		Union[str, os.PathLike]			,						*snake_case						:		Tuple			,						**snake_case						:		Any							):

      """simple docstring"""





      try:
        __lowerCAmelCase			=				BertTokenizer.from_pretrained(lowerCAmelCase_			,						*lowerCAmelCase_			,						**lowerCAmelCase_							)
      except:  # noqa: E722
        from .tokenization_bert_fast import BertTokenizerFast

        __lowerCAmelCase			=				BertTokenizerFast.from_pretrained(lowerCAmelCase_			,						*lowerCAmelCase_			,						**lowerCAmelCase_							)
      return cls.from_tokenizer(lowerCAmelCase_			,						**lowerCAmelCase_							)





    def 	A		(   self						:		Union[str, Any]			,						snake_case						:		Optional[Any]							):

      """simple docstring"""





      if self.do_lower_case:
        __lowerCAmelCase			=				case_fold_utfa(lowerCAmelCase_							)
      __lowerCAmelCase			=				self.tf_tokenizer.tokenize(lowerCAmelCase_							)
      return tokens.merge_dims(1			,						-1							)





    def 	A		(   self						:		str			,						snake_case						:		Union[str, Any]			,						snake_case						:		Tuple=None			,						snake_case						:		str=None			,						snake_case						:		int=None			,						snake_case						:		List[Any]=None			,						snake_case						:		str=None			,						snake_case						:		List[str]=None			,						snake_case						:		Dict=None			,						):

      """simple docstring"""





      if padding is None:
        __lowerCAmelCase			=				self.padding
      if padding not in ("longest", "max_length"):
        raise ValueError('''Padding must be either \'longest\' or \'max_length\'!'''							)
      if max_length is not None and text_pair is not None:
        # Because we have to instantiate a Trimmer to do it properly
        raise ValueError('''max_length cannot be overridden at call time when truncating paired texts!'''							)
      if max_length is None:
        __lowerCAmelCase			=				self.max_length
      if truncation is None:
        __lowerCAmelCase			=				self.truncation
      if pad_to_multiple_of is None:
        __lowerCAmelCase			=				self.pad_to_multiple_of
      if return_token_type_ids is None:
        __lowerCAmelCase			=				self.return_token_type_ids
      if return_attention_mask is None:
        __lowerCAmelCase			=				self.return_attention_mask
      if not isinstance(lowerCAmelCase_			,						tf.Tensor							):
        __lowerCAmelCase			=				tf.convert_to_tensor(lowerCAmelCase_							)
      if text_pair is not None and not isinstance(lowerCAmelCase_			,						tf.Tensor							):
        __lowerCAmelCase			=				tf.convert_to_tensor(lowerCAmelCase_							)
      if text_pair is not None:
        if text.shape.rank > 1:
          raise ValueError('''text argument should not be multidimensional when a text pair is supplied!'''							)
        if text_pair.shape.rank > 1:
          raise ValueError('''text_pair should not be multidimensional!'''							)
      if text.shape.rank == 2:
        __lowerCAmelCase	,						__lowerCAmelCase			=				text[:, 0], text[:, 1]
      __lowerCAmelCase			=				self.unpaired_tokenize(lowerCAmelCase_							)
      if text_pair is None:  # Unpaired text
        if truncation:
          __lowerCAmelCase			=				text[:, : max_length - 2]  # Allow room for special tokens
        __lowerCAmelCase	,						__lowerCAmelCase			=				combine_segments(
            (text,)			,						start_of_sequence_id=self.cls_token_id			,						end_of_segment_id=self.sep_token_id							)
      else:  # Paired text
        __lowerCAmelCase			=				self.unpaired_tokenize(lowerCAmelCase_							)
        if truncation:
          __lowerCAmelCase	,						__lowerCAmelCase			=				self.paired_trimmer.trim([text, text_pair]							)
        __lowerCAmelCase	,						__lowerCAmelCase			=				combine_segments(
            (text, text_pair)			,						start_of_sequence_id=self.cls_token_id			,						end_of_segment_id=self.sep_token_id							)
      if padding == "longest":
        __lowerCAmelCase			=				input_ids.bounding_shape(axis=1							)
        if pad_to_multiple_of is not None:
          # No ceiling division in tensorflow, so we negate floordiv instead
          __lowerCAmelCase			=				pad_to_multiple_of * (-tf.math.floordiv(-pad_length			,						lowerCAmelCase_							))
      else:
        __lowerCAmelCase			=				max_length

      __lowerCAmelCase	,						__lowerCAmelCase			=				pad_model_inputs(lowerCAmelCase_			,						max_seq_length=lowerCAmelCase_			,						pad_value=self.pad_token_id							)
      __lowerCAmelCase			=				{'''input_ids''': input_ids}
      if return_attention_mask:
        __lowerCAmelCase			=				attention_mask
      if return_token_type_ids:
        __lowerCAmelCase	,						__lowerCAmelCase			=				pad_model_inputs(
            lowerCAmelCase_			,						max_seq_length=lowerCAmelCase_			,						pad_value=self.pad_token_id							)
        __lowerCAmelCase			=				token_type_ids
      return output





    def 	A		(   self						:		Dict							):

      """simple docstring"""





      return {
          "vocab_list": self.vocab_list,
          "do_lower_case": self.do_lower_case,
          "cls_token_id": self.cls_token_id,
          "sep_token_id": self.sep_token_id,
          "pad_token_id": self.pad_token_id,
      }







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   __snake_case				(			_a   ):






    '''simple docstring'''





    @staticmethod
    def 	A		(   snake_case						:		ArgumentParser							):

      """simple docstring"""





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






    '''simple docstring'''
    _lowerCAmelCase     =	"""\u001b[1m"""
    _lowerCAmelCase     =	"""\u001b[31m"""
    _lowerCAmelCase     =	"""\u001b[90m"""
    _lowerCAmelCase     =	"""\u001b[0m"""





    @classmethod
    def 	A		(   cls						:		str			,						snake_case						:		Optional[int]							):

      """simple docstring"""





      return f'''{cls._bold}{s}{cls._reset}'''





    @classmethod
    def 	A		(   cls						:		Optional[Any]			,						snake_case						:		str							):

      """simple docstring"""





      return f'''{cls._bold}{cls._red}{s}{cls._reset}'''





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

      """simple docstring"""





      return f'''{cls._gray}{s}{cls._reset}'''


def 					__SCREAMING_SNAKE_CASE  (							__lowercase:		List[List[Union[str, int]]]     ,							__lowercase:		List[str]):



  '''simple docstring'''






  __lowerCAmelCase			=				[max(len(str(__lowercase)) for x in col) for col in zip(*__lowercase     ,							__lowercase)]
  __lowerCAmelCase			=				('''{{:{}}} ''' * len(__lowercase)).format(*__lowercase)
  __lowerCAmelCase			=				[]
  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   __snake_case				:






    '''simple docstring'''





    def __init__(   self						:		List[str]			,						snake_case						:		List[str]							):

      """simple docstring"""





      __lowerCAmelCase			=				args


class   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		List[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   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		int							):

      """simple docstring"""





      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   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		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   __snake_case				(			_a   ):






    '''simple docstring'''





    def 	A		(   self						:		Optional[int]							):

      """simple docstring"""





      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(''''''							)
