

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     snake_case__(					_UpperCamelCase			:    ArgumentParser							)				->Tuple:
									snake_case_       =     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_       =     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_       =     parser.add_parser('''logout'''							,       help='''Log out'''							)
									logout_parser.set_defaults(func=lambda _UpperCamelCase							: LogoutCommand(_UpperCamelCase							)							)

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







			'''simple docstring'''

			SCREAMING_SNAKE_CASE					:       List[Any]						      =    "\u001b[1m"
			SCREAMING_SNAKE_CASE					:       int						      =    "\u001b[31m"
			SCREAMING_SNAKE_CASE					:       Dict						      =    "\u001b[90m"
			SCREAMING_SNAKE_CASE					:       int						      =    "\u001b[0m"







			@classmethod
			def     snake_case__(					cls			:    Dict							,       _UpperCamelCase			:    Optional[int]							)				->Optional[int]:
									return f'''{cls._bold}{s}{cls._reset}'''







			@classmethod
			def     snake_case__(					cls			:    Any							,       _UpperCamelCase			:    List[Any]							)				->Union[str, Any]:
									return f'''{cls._bold}{cls._red}{s}{cls._reset}'''







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






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





class      snake_case_       :







			'''simple docstring'''

			def __init__(					self			:    List[Any]							,       _UpperCamelCase			:    int							)				->Union[str, Any]:
									snake_case_       =     args






class      snake_case_       (		__A ):







			'''simple docstring'''

			def     snake_case__(					self			:    List[Any]							)				->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      snake_case_       (		__A ):







			'''simple docstring'''

			def     snake_case__(					self			:    Optional[int]							)				->Dict:
									print(
									    ANSI.red(
									        '''WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use '''
									        '''`huggingface-cli whoami` instead.'''							)							)
									snake_case_       =     HfFolder.get_token()
									if token is None:
															print('''Not logged in'''							)
															exit()
									try:
															snake_case_,   snake_case_       =     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      snake_case_       (		__A ):







			'''simple docstring'''

			def     snake_case__(					self			:    Tuple							)				->Dict:
									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     snake_case__(					self			:    Union[str, Any]							)				->List[str]:
									print(
									    ANSI.red(
									        '''WARNING! Managing repositories through transformers-cli is deprecated. '''
									        '''Please use `huggingface-cli` instead.'''							)							)
									snake_case_       =     HfFolder.get_token()
									if token is None:
															print('''Not logged in'''							)
															exit(1							)
									try:
															snake_case_       =     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_       =     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_       =     whoami(_UpperCamelCase							)
									snake_case_       =     self.args.organization if self.args.organization is not None else user
									snake_case_       =     f'''{namespace}/{self.args.name}'''
									print(f'''You are about to create {ANSI.bold(_UpperCamelCase							)}'''							)

									if not self.args.yes:
															snake_case_       =     input('''Proceed? [Y/n] '''							).lower()
															if not (choice == "" or choice == "y" or choice == "yes"):
																					print('''Abort'''							)
																					exit()
									try:
															snake_case_       =     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(''''''							)


import concurrent.futures
import json
import os
import shutil
import tempfile
import unittest

from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers.testing_utils import require_tokenizers

from ..test_tokenization_common import TokenizerTesterMixin





@require_tokenizers
class      snake_case_       (		__A     ,	unittest.TestCase ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE					:       str						      =    PreTrainedTokenizerFast
			SCREAMING_SNAKE_CASE					:       List[str]						      =    False
			SCREAMING_SNAKE_CASE					:       Tuple						      =    True
			SCREAMING_SNAKE_CASE					:       str						      =    "tokenizer_file"







			def     snake_case__(					self			:    Dict							)				->int:
									snake_case_       =     False  # because we don't have pretrained_vocab_files_map
									super().setUp()
									snake_case_       =     True

									snake_case_       =     ['''robot-test/dummy-tokenizer-fast''', '''robot-test/dummy-tokenizer-wordlevel''']
									snake_case_       =     '''SaulLu/dummy-tokenizer-bytelevel-bpe'''

									# Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
									snake_case_       =     [(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths]

									snake_case_       =     PreTrainedTokenizerFast.from_pretrained(model_paths[0]							)
									tokenizer.save_pretrained(self.tmpdirname							)







			def     snake_case__(					self			:    Union[str, Any]							)				->Dict:
									# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
									# model
									pass







			def     snake_case__(					self			:    str							)				->Any:
									# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
									# model
									pass







			def     snake_case__(					self			:    List[Any]							)				->str:
									# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
									# model
									pass







			def     snake_case__(					self			:    str							)				->List[Any]:
									# PreTrainedTokenizerFast doesn't have tokenizer_file in its signature
									pass







			def     snake_case__(					self			:    Any							)				->Union[str, Any]:
									snake_case_       =     self.tmpdirname
									# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
									for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
															with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''							):
																					try:
																											snake_case_       =     tempfile.mkdtemp()
																											snake_case_       =     self.rust_tokenizer_class.from_pretrained(_UpperCamelCase							,       **_UpperCamelCase							)

																											tokenizer.save_pretrained(self.tmpdirname							)
																											super().test_training_new_tokenizer()
																					finally:
																											# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
																											# is restored
																											shutil.rmtree(self.tmpdirname							)
																											snake_case_       =     tmpdirname_orig







			def     snake_case__(					self			:    List[str]							)				->List[Any]:
									snake_case_       =     self.tmpdirname
									# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
									for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
															with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''							):
																					try:
																											snake_case_       =     tempfile.mkdtemp()
																											snake_case_       =     self.rust_tokenizer_class.from_pretrained(_UpperCamelCase							,       **_UpperCamelCase							)

																											tokenizer.save_pretrained(self.tmpdirname							)
																											super().test_training_new_tokenizer_with_special_tokens_change()
																					finally:
																											# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
																											# is restored
																											shutil.rmtree(self.tmpdirname							)
																											snake_case_       =     tmpdirname_orig







			def     snake_case__(					self			:    Optional[int]							)				->Optional[Any]:
									snake_case_       =     self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name							)

									snake_case_       =     ('''a''' for _ in range(1_0_0_0							))
									snake_case_       =     tokenizer.train_new_from_iterator(text_iterator=_UpperCamelCase							,       length=1_0_0_0							,       vocab_size=5_0							)

									snake_case_       =     new_tokenizer.encode('''a🤗'''							)
									self.assertEqual(_UpperCamelCase							,       [6_4, 1_7_2, 2_5_3, 9_7, 2_4_5]							)






@require_tokenizers
class      snake_case_       (		unittest.TestCase ):







			'''simple docstring'''

			def     snake_case__(					self			:    Optional[int]							)				->int:
									snake_case_       =     AutoTokenizer.from_pretrained('''bert-base-cased'''							)
									snake_case_       =     json.loads(tokenizer._tokenizer.to_str()							)
									snake_case_       =     len(_UpperCamelCase							)

									with tempfile.TemporaryDirectory() as tmp_dir:
															# Hack to save this in the tokenizer_config.json
															snake_case_       =     ['''tokenizer.4.0.0.json''']
															tokenizer.save_pretrained(_UpperCamelCase							)
															json.dump(_UpperCamelCase							,       open(os.path.join(_UpperCamelCase							,       '''tokenizer.4.0.0.json'''							)							,       '''w'''							)							)

															# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
															snake_case_       =     AutoTokenizer.from_pretrained(_UpperCamelCase							)
															self.assertEqual(len(_UpperCamelCase							)							,       len(_UpperCamelCase							) + 1							)
															snake_case_       =     json.loads(new_tokenizer._tokenizer.to_str()							)
															self.assertIn('''huggingface'''							,       json_tokenizer['''model''']['''vocab''']							)

															# Will need to be adjusted if we reach v42 and this test is still here.
															# Should pick the old tokenizer file as the version of Transformers is < 4.0.0
															shutil.move(os.path.join(_UpperCamelCase							,       '''tokenizer.4.0.0.json'''							)							,       os.path.join(_UpperCamelCase							,       '''tokenizer.42.0.0.json'''							)							)
															snake_case_       =     ['''tokenizer.42.0.0.json''']
															tokenizer.save_pretrained(_UpperCamelCase							)
															snake_case_       =     AutoTokenizer.from_pretrained(_UpperCamelCase							)
															self.assertEqual(len(_UpperCamelCase							)							,       len(_UpperCamelCase							)							)
															snake_case_       =     json.loads(new_tokenizer._tokenizer.to_str()							)
															self.assertNotIn('''huggingface'''							,       json_tokenizer['''model''']['''vocab''']							)







			def     snake_case__(					self			:    List[str]							)				->Optional[Any]:
									# This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
									snake_case_       =     '''hf-internal-testing/test-two-tokenizers'''

									# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
									snake_case_       =     AutoTokenizer.from_pretrained(_UpperCamelCase							)
									self.assertEqual(len(_UpperCamelCase							)							,       2_8_9_9_7							)
									snake_case_       =     json.loads(tokenizer._tokenizer.to_str()							)
									self.assertIn('''huggingface'''							,       json_tokenizer['''model''']['''vocab''']							)

									# Testing an older version by monkey-patching the version in the module it's used.
									import transformers as old_transformers

									snake_case_       =     '''3.0.0'''
									snake_case_       =     old_transformers.models.auto.AutoTokenizer.from_pretrained(_UpperCamelCase							)
									self.assertEqual(len(_UpperCamelCase							)							,       2_8_9_9_6							)
									snake_case_       =     json.loads(old_tokenizer._tokenizer.to_str()							)
									self.assertNotIn('''huggingface'''							,       json_tokenizer['''model''']['''vocab''']							)






@require_tokenizers
class      snake_case_       (		unittest.TestCase ):







			'''simple docstring'''

			def     snake_case__(					self			:    str							)				->Optional[int]:
									# See https://github.com/huggingface/transformers/pull/12550
									# and https://github.com/huggingface/tokenizers/issues/537
									snake_case_       =     PreTrainedTokenizerFast.from_pretrained('''robot-test/dummy-tokenizer-wordlevel'''							)
									snake_case_       =     '''The Matrix is a 1999 science fiction action film.'''

									with concurrent.futures.ThreadPoolExecutor() as executor:
															snake_case_       =     [executor.submit(self.fetch							,       _UpperCamelCase							,       _UpperCamelCase							) for i in range(1_0							)]
															snake_case_       =     [future.result() for future in futures]
															self.assertEqual(_UpperCamelCase							,       [[1, 1_0, 0, 8, 0, 1_8, 0, 0, 0, 2] for i in range(1_0							)]							)







			def     snake_case__(					self			:    Optional[int]							,       _UpperCamelCase			:    Dict							,       _UpperCamelCase			:    str							)				->Tuple:
									return tokenizer.encode(_UpperCamelCase							,       truncation='''longest_first'''							,       padding='''longest'''							)