




"""simple docstring"""

import gc
import unittest

from transformers import CTRLConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
       import torch

       from transformers import (
           CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
           CTRLForSequenceClassification,
           CTRLLMHeadModel,
           CTRLModel,
       )





class     lowercase_	:



 '''simple docstring'''

 def __init__(			self	:	Union[str, Any]   ,							_UpperCAmelCase	:	Optional[Any]   ,							_UpperCAmelCase	:	Optional[int]=14   ,							_UpperCAmelCase	:	Union[str, Any]=7   ,							_UpperCAmelCase	:	List[Any]=True   ,							_UpperCAmelCase	:	List[Any]=True   ,							_UpperCAmelCase	:	Tuple=True   ,							_UpperCAmelCase	:	Any=True   ,							_UpperCAmelCase	:	List[str]=True   ,							_UpperCAmelCase	:	Dict=99   ,							_UpperCAmelCase	:	Tuple=32   ,							_UpperCAmelCase	:	Any=5   ,							_UpperCAmelCase	:	Optional[int]=4   ,							_UpperCAmelCase	:	Optional[int]=37   ,							_UpperCAmelCase	:	List[str]="gelu"   ,							_UpperCAmelCase	:	str=0.1   ,							_UpperCAmelCase	:	Union[str, Any]=0.1   ,							_UpperCAmelCase	:	List[str]=512   ,							_UpperCAmelCase	:	List[Any]=16   ,							_UpperCAmelCase	:	Tuple=2   ,							_UpperCAmelCase	:	Dict=0.02   ,							_UpperCAmelCase	:	Dict=3   ,							_UpperCAmelCase	:	Dict=4   ,							_UpperCAmelCase	:	List[Any]=None   ,							):
       _A        =       parent
       _A        =       batch_size
       _A        =       seq_length
       _A        =       is_training
       _A        =       use_token_type_ids
       _A        =       use_input_mask
       _A        =       use_labels
       _A        =       use_mc_token_ids
       _A        =       vocab_size
       _A        =       hidden_size
       _A        =       num_hidden_layers
       _A        =       num_attention_heads
       _A        =       intermediate_size
       _A        =       hidden_act
       _A        =       hidden_dropout_prob
       _A        =       attention_probs_dropout_prob
       _A        =       max_position_embeddings
       _A        =       type_vocab_size
       _A        =       type_sequence_label_size
       _A        =       initializer_range
       _A        =       num_labels
       _A        =       num_choices
       _A        =       scope
       _A        =       self.vocab_size - 1

 def       lowerCAmelCase_							(			self	:	int		):
       _A        =       ids_tensor([self.batch_size, self.seq_length]   ,							self.vocab_size		)

       _A        =       None
       if self.use_input_mask:
             _A        =       random_attention_mask([self.batch_size, self.seq_length]		)

       _A        =       None
       if self.use_token_type_ids:
             _A        =       ids_tensor([self.batch_size, self.seq_length]   ,							self.type_vocab_size		)

       _A        =       None
       if self.use_mc_token_ids:
             _A        =       ids_tensor([self.batch_size, self.num_choices]   ,							self.seq_length		)

       _A        =       None
       _A        =       None
       _A        =       None
       if self.use_labels:
             _A        =       ids_tensor([self.batch_size]   ,							self.type_sequence_label_size		)
             _A        =       ids_tensor([self.batch_size, self.seq_length]   ,							self.num_labels		)
             _A        =       ids_tensor([self.batch_size]   ,							self.num_choices		)

       _A        =       self.get_config()

       _A        =       ids_tensor([self.num_hidden_layers, self.num_attention_heads]   ,							2		)

       return (
           config,
           input_ids,
           input_mask,
           head_mask,
           token_type_ids,
           mc_token_ids,
           sequence_labels,
           token_labels,
           choice_labels,
       )

 def       lowerCAmelCase_							(			self	:	List[str]		):
       return CTRLConfig(
           vocab_size=self.vocab_size   ,							n_embd=self.hidden_size   ,							n_layer=self.num_hidden_layers   ,							n_head=self.num_attention_heads   ,							n_positions=self.max_position_embeddings   ,							pad_token_id=self.pad_token_id   ,							)

 def       lowerCAmelCase_							(			self	:	List[Any]   ,							_UpperCAmelCase	:	Tuple   ,							_UpperCAmelCase	:	Optional[Any]   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	Optional[Any]   ,							_UpperCAmelCase	:	List[Any]   ,							*_UpperCAmelCase	:	Dict		):
       _A        =       CTRLModel(config=__A		)
       model.to(__A		)
       model.eval()

       model(__A   ,							token_type_ids=__A   ,							head_mask=__A		)
       model(__A   ,							token_type_ids=__A		)
       _A        =       model(__A		)
       self.parent.assertEqual(result.last_hidden_state.shape   ,							(self.batch_size, self.seq_length, self.hidden_size)		)
       self.parent.assertEqual(len(result.past_key_values		)   ,							config.n_layer		)

 def       lowerCAmelCase_							(			self	:	List[Any]   ,							_UpperCAmelCase	:	Dict   ,							_UpperCAmelCase	:	Tuple   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	Optional[Any]   ,							_UpperCAmelCase	:	Tuple   ,							*_UpperCAmelCase	:	Tuple		):
       _A        =       CTRLLMHeadModel(__A		)
       model.to(__A		)
       model.eval()

       _A        =       model(__A   ,							token_type_ids=__A   ,							labels=__A		)
       self.parent.assertEqual(result.loss.shape   ,							()		)
       self.parent.assertEqual(result.logits.shape   ,							(self.batch_size, self.seq_length, self.vocab_size)		)

 def       lowerCAmelCase_							(			self	:	Dict		):
       _A        =       self.prepare_config_and_inputs()

       (
           _A	
       )        =       config_and_inputs

       _A        =       {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask}

       return config, inputs_dict



 def       lowerCAmelCase_							(			self	:	List[str]   ,							_UpperCAmelCase	:	Union[str, Any]   ,							_UpperCAmelCase	:	List[str]   ,							_UpperCAmelCase	:	List[Any]   ,							_UpperCAmelCase	:	List[str]   ,							*_UpperCAmelCase	:	Any		):
       _A        =       self.num_labels
       _A        =       CTRLForSequenceClassification(__A		)
       model.to(__A		)
       model.eval()
       _A        =       ids_tensor([self.batch_size]   ,							self.type_sequence_label_size		)
       _A        =       model(__A   ,							token_type_ids=__A   ,							labels=__A		)
       self.parent.assertEqual(result.logits.shape   ,							(self.batch_size, self.num_labels)		)





@require_torch
class     lowercase_	(					A__      ,     A__      ,     A__      ,     unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase   :					Optional[int]				  =     (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
 UpperCAmelCase   :					Optional[Any]				  =     (CTRLLMHeadModel,) if is_torch_available() else ()
 UpperCAmelCase   :					Tuple				  =     (
     {
         "feature-extraction": CTRLModel,
         "text-classification": CTRLForSequenceClassification,
         "text-generation": CTRLLMHeadModel,
         "zero-shot": CTRLForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 UpperCAmelCase   :					int				  =     True
 UpperCAmelCase   :					int				  =     False
 UpperCAmelCase   :					List[Any]				  =     False

 def       lowerCAmelCase_							(			self	:	Union[str, Any]   ,							_UpperCAmelCase	:	Optional[Any]   ,							_UpperCAmelCase	:	List[Any]   ,							_UpperCAmelCase	:	Optional[Any]   ,							_UpperCAmelCase	:	List[str]   ,							_UpperCAmelCase	:	Dict		):
       if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
             # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
             # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
             # config could not be created.
             return True

       return False

 def       lowerCAmelCase_							(			self	:	List[Any]		):
       _A        =       CTRLModelTester(self		)
       _A        =       ConfigTester(self   ,							config_class=__A   ,							n_embd=37		)

 def       lowerCAmelCase_							(			self	:	List[Any]		):
       super().tearDown()
       # clean-up as much as possible GPU memory occupied by PyTorch
       gc.collect()
       torch.cuda.empty_cache()

 def       lowerCAmelCase_							(			self	:	Tuple		):
       self.config_tester.run_common_tests()

 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       _A        =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_ctrl_model(*__A		)

 def       lowerCAmelCase_							(			self	:	Optional[Any]		):
       _A        =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_lm_head_model(*__A		)

 @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'		)
 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       pass

 @slow
 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             _A        =       CTRLModel.from_pretrained(__A		)
             self.assertIsNotNone(__A		)



 @unittest.skip('The model doesn\'t support left padding'		)  # and it's not used enough to be worth fixing :)
 def       lowerCAmelCase_							(			self	:	Union[str, Any]		):
       pass





@require_torch
class     lowercase_	(					unittest.TestCase							):



 '''simple docstring'''

 def       lowerCAmelCase_							(			self	:	str		):
       super().tearDown()
       # clean-up as much as possible GPU memory occupied by PyTorch
       gc.collect()
       torch.cuda.empty_cache()



 @slow
 def       lowerCAmelCase_							(			self	:	Any		):
       _A        =       CTRLLMHeadModel.from_pretrained('ctrl'		)
       model.to(__A		)
       _A        =       torch.tensor(
           [[11_859, 0, 1_611, 8]]   ,							dtype=torch.long   ,							device=__A		)  # Legal the president is
       _A        =       [
           11_859,
           0,
           1_611,
           8,
           5,
           150,
           26_449,
           2,
           19,
           348,
           469,
           3,
           2_595,
           48,
           20_740,
           246_533,
           246_533,
           19,
           30,
           5,
       ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

       _A        =       model.generate(__A   ,							do_sample=__A		)
       self.assertListEqual(output_ids[0].tolist()   ,							__A		)







"""simple docstring"""

def 						_snake_case					( _snake_case							: str							)   -> str:






      '''simple docstring'''


      _A        =       ''
      for ch in key:
            if ch == " " or ch not in key_no_dups and ch.isalpha():
                  key_no_dups += ch
      return key_no_dups






def 						_snake_case					( _snake_case							: str							)   -> dict[str, str]:






      '''simple docstring'''


      _A        =       [chr(i + 65							) for i in range(26							)]
      # Remove duplicate characters from key
      _A        =       remove_duplicates(key.upper()							)
      _A        =       len(_snake_case							)
      # First fill cipher with key characters
      _A        =       {alphabet[i]: char for i, char in enumerate(_snake_case							)}
      # Then map remaining characters in alphabet to
      # the alphabet from the beginning
      for i in range(len(_snake_case							)    ,  26							):
            _A        =       alphabet[i - offset]
            # Ensure we are not mapping letters to letters previously mapped
            while char in key:
                  offset -= 1
                  _A        =       alphabet[i - offset]
            _A        =       char
      return cipher_alphabet






def 						_snake_case					( _snake_case							: str    ,  _snake_case							: dict[str, str]							)   -> str:






      '''simple docstring'''


      return "".join(cipher_map.get(_snake_case    ,  _snake_case							) for ch in message.upper()							)






def 						_snake_case					( _snake_case							: str    ,  _snake_case							: dict[str, str]							)   -> str:






      '''simple docstring'''


      _A        =       {v: k for k, v in cipher_map.items()}
      return "".join(rev_cipher_map.get(_snake_case    ,  _snake_case							) for ch in message.upper()							)






def 						_snake_case					( )   -> None:






      '''simple docstring'''


      _A        =       input('Enter message to encode or decode: '							).strip()
      _A        =       input('Enter keyword: '							).strip()
      _A        =       input('Encipher or decipher? E/D:'							).strip()[0].lower()
      try:
            _A        =       {'e': encipher, 'd': decipher}[option]
      except KeyError:
            raise KeyError('invalid input option'							)
      _A        =       create_cipher_map(_snake_case							)
      print(func(_snake_case    ,  _snake_case							)							)


if __name__ == "__main__":
       import doctest

       doctest.testmod()
       main()

