


"""simple docstring"""



import unittest

from transformers import SpeechaTextaConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers.models.speech_to_text_a.modeling_speech_to_text_a import (
		    SpeechaTextaDecoder,
		    SpeechaTextaForCausalLM,
		)







@require_torch
class       __a	:







				def __init__(   self			,  UpperCAmelCase			,  UpperCAmelCase=99			,  UpperCAmelCase=13			,  UpperCAmelCase=16			,  UpperCAmelCase=7			,  UpperCAmelCase=True			,  UpperCAmelCase=True			,  UpperCAmelCase=True			,  UpperCAmelCase=False			,  UpperCAmelCase=True			,  UpperCAmelCase=2			,  UpperCAmelCase=32			,  UpperCAmelCase=4			,  UpperCAmelCase=4			,  UpperCAmelCase=30			,  UpperCAmelCase=0			,  UpperCAmelCase=1			,  UpperCAmelCase=2			,  UpperCAmelCase=None			,  ):

					'''simple docstring'''






					lowerCAmelCase_			       = parent
					lowerCAmelCase_			       = batch_size
					lowerCAmelCase_			       = decoder_seq_length
					# For common tests
					lowerCAmelCase_			       = self.decoder_seq_length
					lowerCAmelCase_			       = is_training
					lowerCAmelCase_			       = use_attention_mask
					lowerCAmelCase_			       = use_labels

					lowerCAmelCase_			       = vocab_size
					lowerCAmelCase_			       = d_model
					lowerCAmelCase_			       = d_model
					lowerCAmelCase_			       = decoder_layers
					lowerCAmelCase_			       = decoder_layers
					lowerCAmelCase_			       = decoder_ffn_dim
					lowerCAmelCase_			       = decoder_attention_heads
					lowerCAmelCase_			       = decoder_attention_heads
					lowerCAmelCase_			       = eos_token_id
					lowerCAmelCase_			       = bos_token_id
					lowerCAmelCase_			       = pad_token_id
					lowerCAmelCase_			       = decoder_start_token_id
					lowerCAmelCase_			       = use_cache
					lowerCAmelCase_			       = max_position_embeddings

					lowerCAmelCase_			       = None
					lowerCAmelCase_			       = decoder_seq_length
					lowerCAmelCase_			       = 2
					lowerCAmelCase_			       = 1







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_			       = ids_tensor([self.batch_size, self.decoder_seq_length]			,  self.vocab_size      )

					lowerCAmelCase_			       = None
					if self.use_attention_mask:
						lowerCAmelCase_			       = ids_tensor([self.batch_size, self.decoder_seq_length]			,  vocab_size=2      )

					lowerCAmelCase_			       = None
					if self.use_labels:
						lowerCAmelCase_			       = ids_tensor([self.batch_size, self.decoder_seq_length]			,  self.vocab_size      )

					lowerCAmelCase_			       = SpeechaTextaConfig(
					    vocab_size=self.vocab_size			,  d_model=self.d_model			,  decoder_layers=self.decoder_layers			,  decoder_ffn_dim=self.decoder_ffn_dim			,  decoder_attention_heads=self.decoder_attention_heads			,  eos_token_id=self.eos_token_id			,  bos_token_id=self.bos_token_id			,  use_cache=self.use_cache			,  pad_token_id=self.pad_token_id			,  decoder_start_token_id=self.decoder_start_token_id			,  max_position_embeddings=self.max_position_embeddings			,  )

					return (
					    config,
					    input_ids,
					    attention_mask,
					    lm_labels,
					)







				def     lowerCamelCase_    (   self			,  UpperCAmelCase			,  UpperCAmelCase			,  UpperCAmelCase			,  UpperCAmelCase			,  ):

					'''simple docstring'''






					lowerCAmelCase_			       = True
					lowerCAmelCase_			       = SpeechaTextaDecoder(config=UpperCAmelCase      ).to(UpperCAmelCase      ).eval()
					lowerCAmelCase_			       = input_ids[:2]

					input_ids[input_ids == 0] += 1
					# first forward pass
					lowerCAmelCase_			       = model(UpperCAmelCase			,  use_cache=UpperCAmelCase      )
					lowerCAmelCase_			       = model(UpperCAmelCase      )
					lowerCAmelCase_			       = model(UpperCAmelCase			,  use_cache=UpperCAmelCase      )

					self.parent.assertTrue(len(UpperCAmelCase      ) == len(UpperCAmelCase      )      )
					self.parent.assertTrue(len(UpperCAmelCase      ) == len(UpperCAmelCase      ) + 1      )

					lowerCAmelCase_			       = outputs['''past_key_values''']

					# create hypothetical next token and extent to next_input_ids
					lowerCAmelCase_			       = ids_tensor((2, 1)			,  config.vocab_size - 1      ) + 1

					# append to next input_ids and
					lowerCAmelCase_			       = torch.cat([input_ids, next_tokens]			,  dim=-1      )

					print(UpperCAmelCase      )

					lowerCAmelCase_			       = model(UpperCAmelCase      )['''last_hidden_state''']
					lowerCAmelCase_			       = model(UpperCAmelCase			,  past_key_values=UpperCAmelCase      )['''last_hidden_state''']

					# select random slice
					lowerCAmelCase_			       = ids_tensor((1,)			,  output_from_past.shape[-1]      ).item()
					lowerCAmelCase_			       = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
					lowerCAmelCase_			       = output_from_past[:, 0, random_slice_idx].detach()

					# test that outputs are equal for slice
					assert torch.allclose(UpperCAmelCase			,  UpperCAmelCase			,  atol=1E-3      )







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_			       = self.prepare_config_and_inputs()
					(
					    (
					    lowerCAmelCase_
					)       ,  (
					    lowerCAmelCase_
					)       ,  (
					    lowerCAmelCase_
					)       ,  (
					    lowerCAmelCase_
					)       ,  
					)			       = config_and_inputs

					lowerCAmelCase_			       = {
					    '''input_ids''': input_ids,
					    '''attention_mask''': attention_mask,
					}
					return config, inputs_dict







@require_torch
class       __a	(   __snake_case				, __snake_case				, __snake_case				, unittest.TestCase       ):
				lowerCamelCase    :					Any 					=(SpeechaTextaDecoder, SpeechaTextaForCausalLM) if is_torch_available() else ()
				lowerCamelCase    :					Optional[Any] 					=(SpeechaTextaForCausalLM,) if is_torch_available() else ()
				lowerCamelCase    :					str 					={'text-generation': SpeechaTextaForCausalLM} if is_torch_available() else {}
				lowerCamelCase    :					Any 					=True
				lowerCamelCase    :					Tuple 					=False







				def     lowerCamelCase_    (   self			,  ):

					'''simple docstring'''






					lowerCAmelCase_			       = SpeechaTextaStandaloneDecoderModelTester(self			,  is_training=UpperCAmelCase      )
					lowerCAmelCase_			       = ConfigTester(self			,  config_class=UpperCAmelCase      )







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					pass







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					pass







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					pass







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					self.config_tester.run_common_tests()







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_			       = self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_decoder_model_past(*UpperCAmelCase      )







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					return



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







				@staticmethod
				def     lowerCamelCase_    (   UpperCAmelCase      ):

					'''simple docstring'''






					lowerCAmelCase_			       = parser.add_parser('''login'''			,  help='''Log in using the same credentials as on huggingface.co'''      )
					login_parser.set_defaults(func=lambda UpperCAmelCase      : LoginCommand(UpperCAmelCase      )      )
					lowerCAmelCase_			       = 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      )      )
					lowerCAmelCase_			       = parser.add_parser('''logout'''			,  help='''Log out'''      )
					logout_parser.set_defaults(func=lambda UpperCAmelCase      : LogoutCommand(UpperCAmelCase      )      )

					# 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=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       __a	:
				lowerCamelCase    :					Dict 					='\u001b[1m'
				lowerCamelCase    :					Tuple 					='\u001b[31m'
				lowerCamelCase    :					List[str] 					='\u001b[90m'
				lowerCamelCase    :					Any 					='\u001b[0m'







				@classmethod
				def     lowerCamelCase_    (   cls			,  UpperCAmelCase      ):

					'''simple docstring'''






					return F"""{cls._bold}{s}{cls._reset}"""







				@classmethod
				def     lowerCamelCase_    (   cls			,  UpperCAmelCase      ):

					'''simple docstring'''






					return F"""{cls._bold}{cls._red}{s}{cls._reset}"""







				@classmethod
				def     lowerCamelCase_    (   cls			,  UpperCAmelCase      ):

					'''simple docstring'''






					return F"""{cls._gray}{s}{cls._reset}"""




def     UpperCAmelCase    (					_lowercase   :      List[List[Union[str, int]]] ,      _lowercase   :      List[str]  )	->   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       __a	:







				def __init__(   self			,  UpperCAmelCase      ):

					'''simple docstring'''






					lowerCAmelCase_			       = args







class       __a	(   __snake_case       ):







				def     lowerCamelCase_    (   self      ):

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







				def     lowerCamelCase_    (   self      ):

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







				def     lowerCamelCase_    (   self      ):

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







				def     lowerCamelCase_    (   self      ):

					'''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(UpperCAmelCase      )
					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(UpperCAmelCase      )}"""      )

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