




from __future__ import annotations

import unittest

from transformers import CTRLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers.models.ctrl.modeling_tf_ctrl import (
      TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFCTRLForSequenceClassification,
      TFCTRLLMHeadModel,
      TFCTRLModel,
  )
class      _UpperCamelCase (			lowerCAmelCase						):
      def __init__(     self				:int	, lowerCamelCase				:Union[str, Any]	, )       ->     List[str]:
       UpperCAmelCase__								=  parent
       UpperCAmelCase__								=  13
       UpperCAmelCase__								=  7
       UpperCAmelCase__								=  True
       UpperCAmelCase__								=  True
       UpperCAmelCase__								=  True
       UpperCAmelCase__								=  True
       UpperCAmelCase__								=  True
       UpperCAmelCase__								=  99
       UpperCAmelCase__								=  32
       UpperCAmelCase__								=  2
       UpperCAmelCase__								=  4
       UpperCAmelCase__								=  37
       UpperCAmelCase__								=  "gelu"
       UpperCAmelCase__								=  0.1
       UpperCAmelCase__								=  0.1
       UpperCAmelCase__								=  512
       UpperCAmelCase__								=  16
       UpperCAmelCase__								=  2
       UpperCAmelCase__								=  0.02
       UpperCAmelCase__								=  3
       UpperCAmelCase__								=  4
       UpperCAmelCase__								=  None
       UpperCAmelCase__								=  self.vocab_size - 1
      def 		UpperCAmelCase_  (     self				:Optional[int] )       ->     Any:
       UpperCAmelCase__								=  ids_tensor([self.batch_size, self.seq_length]	, self.vocab_size )

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

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

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

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

       UpperCAmelCase__								=  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	, )

       UpperCAmelCase__								=  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 		UpperCAmelCase_  (     self				:Tuple	, lowerCamelCase				:Optional[Any]	, lowerCamelCase				:Any	, lowerCamelCase				:Tuple	, lowerCamelCase				:Optional[Any]	, lowerCamelCase				:Union[str, Any]	, *lowerCamelCase				:Optional[int] )       ->     List[Any]:
       UpperCAmelCase__								=  TFCTRLModel(config=lowerCamelCase )
       UpperCAmelCase__								=  {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
       UpperCAmelCase__								=  model(lowerCamelCase )

       UpperCAmelCase__								=  [input_ids, None, input_mask]  # None is the input for 'past'
       UpperCAmelCase__								=  model(lowerCamelCase )

       UpperCAmelCase__								=  model(lowerCamelCase )

       self.parent.assertEqual(result.last_hidden_state.shape	, (self.batch_size, self.seq_length, self.hidden_size) )
      def 		UpperCAmelCase_  (     self				:int	, lowerCamelCase				:Union[str, Any]	, lowerCamelCase				:str	, lowerCamelCase				:List[str]	, lowerCamelCase				:List[Any]	, lowerCamelCase				:Optional[Any]	, *lowerCamelCase				:Union[str, Any] )       ->     Optional[Any]:
       UpperCAmelCase__								=  TFCTRLLMHeadModel(config=lowerCamelCase )
       UpperCAmelCase__								=  {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
       UpperCAmelCase__								=  model(lowerCamelCase )
       self.parent.assertEqual(result.logits.shape	, (self.batch_size, self.seq_length, self.vocab_size) )
      def 		UpperCAmelCase_  (     self				:Any	, lowerCamelCase				:Tuple	, lowerCamelCase				:str	, lowerCamelCase				:int	, lowerCamelCase				:List[str]	, lowerCamelCase				:Union[str, Any]	, *lowerCamelCase				:Optional[int] )       ->     Any:
       UpperCAmelCase__								=  self.num_labels
       UpperCAmelCase__								=  ids_tensor([self.batch_size]	, self.type_sequence_label_size )
       UpperCAmelCase__								=  {
           "input_ids": input_ids,
           "token_type_ids": token_type_ids,
           "labels": sequence_labels,
       }
       UpperCAmelCase__								=  TFCTRLForSequenceClassification(lowerCamelCase )
       UpperCAmelCase__								=  model(lowerCamelCase )
       self.parent.assertEqual(result.logits.shape	, (self.batch_size, self.num_labels) )







      def 		UpperCAmelCase_  (     self				:Any )       ->     List[Any]:
       UpperCAmelCase__								=  self.prepare_config_and_inputs()

       (
           (
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	
       )								=  config_and_inputs

       UpperCAmelCase__								=  {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
       return config, inputs_dict



@require_tf
class      _UpperCamelCase (			lowerCAmelCase		,    lowerCAmelCase		,    unittest.TestCase						):
      UpperCAmelCase_            =						(TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
      UpperCAmelCase_            =						(TFCTRLLMHeadModel,) if is_tf_available() else ()
      UpperCAmelCase_            =						(
          {
              """feature-extraction""": TFCTRLModel,
              """text-classification""": TFCTRLForSequenceClassification,
              """text-generation""": TFCTRLLMHeadModel,
              """zero-shot""": TFCTRLForSequenceClassification,
          }
          if is_tf_available()
          else {}
      )
      UpperCAmelCase_            =						False
      UpperCAmelCase_            =						False
      def 		UpperCAmelCase_  (     self				:Optional[Any]	, lowerCamelCase				:Tuple	, lowerCamelCase				:Optional[int]	, lowerCamelCase				:List[str]	, lowerCamelCase				:Any	, lowerCamelCase				:Tuple )       ->     Optional[Any]:
       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 		UpperCAmelCase_  (     self				:int )       ->     Any:
       UpperCAmelCase__								=  TFCTRLModelTester(self )
       UpperCAmelCase__								=  ConfigTester(self	, config_class=lowerCamelCase	, n_embd=37 )
      def 		UpperCAmelCase_  (     self				:Optional[int] )       ->     Tuple:
       self.config_tester.run_common_tests()
      def 		UpperCAmelCase_  (     self				:List[str] )       ->     Tuple:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_ctrl_model(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:str )       ->     Any:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_ctrl_lm_head(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Union[str, Any] )       ->     Any:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_ctrl_for_sequence_classification(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Optional[int] )       ->     Any:
       UpperCAmelCase__	,	UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs_for_common()
       UpperCAmelCase__								=  [TFCTRLLMHeadModel]
       UpperCAmelCase__								=  [TFCTRLForSequenceClassification]

       for model_class in self.all_model_classes:
        UpperCAmelCase__								=  model_class(lowerCamelCase )
        model.build()  # may be needed for the get_bias() call below
        assert isinstance(model.get_input_embeddings()	, tf.keras.layers.Layer )

        if model_class in list_lm_models:
         UpperCAmelCase__								=  model.get_output_embeddings()
         assert isinstance(lowerCamelCase	, tf.keras.layers.Layer )
         UpperCAmelCase__								=  model.get_bias()
         assert isinstance(lowerCamelCase	, lowerCamelCase )
         for k, v in name.items():
          assert isinstance(lowerCamelCase	, tf.Variable )
        elif model_class in list_other_models_with_output_ebd:
         UpperCAmelCase__								=  model.get_output_embeddings()
         assert isinstance(lowerCamelCase	, tf.keras.layers.Layer )
         UpperCAmelCase__								=  model.get_bias()
         assert name is None
        else:
         UpperCAmelCase__								=  model.get_output_embeddings()
         assert x is None
         UpperCAmelCase__								=  model.get_bias()
         assert name is None







      @slow
      def 		UpperCAmelCase_  (     self				:Any )       ->     Dict:
       for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCAmelCase__								=  TFCTRLModel.from_pretrained(lowerCamelCase )
        self.assertIsNotNone(lowerCamelCase )



@require_tf
class      _UpperCamelCase (			unittest.TestCase						):
      @slow
      def 		UpperCAmelCase_  (     self				:Dict )       ->     Tuple:
       UpperCAmelCase__								=  TFCTRLLMHeadModel.from_pretrained("ctrl" )
       UpperCAmelCase__								=  tf.convert_to_tensor([[1_1859, 0, 1611, 8]]	, dtype=tf.intaa )  # Legal the president is
       UpperCAmelCase__								=  [
           1_1859,
           0,
           1611,
           8,
           5,
           150,
           2_6449,
           2,
           19,
           348,
           469,
           3,
           2595,
           48,
           2_0740,
           24_6533,
           24_6533,
           19,
           30,
           5,
       ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

       UpperCAmelCase__								=  model.generate(lowerCamelCase	, do_sample=lowerCamelCase )
       self.assertListEqual(output_ids[0].numpy().tolist()	, lowerCamelCase )











from __future__ import annotations

from string import ascii_letters



def   lowerCAmelCase						(						_lowerCAmelCase							:				str  ,							_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				str | None = None		):




 """simple docstring"""







 UpperCAmelCase__								=  alphabet or ascii_letters

 # The final result string
 UpperCAmelCase__								=  ""

 for character in input_string:
  if character not in alpha:
   # Append without encryption if character is not in the alphabet
   result += character
  else:
   # Get the index of the new key and make sure it isn't too large
   UpperCAmelCase__								=  (alpha.index(_lowerCAmelCase		) + key) % len(_lowerCAmelCase		)

   # Append the encoded character to the alphabet
   result += alpha[new_key]

 return result



def   lowerCAmelCase						(						_lowerCAmelCase							:				str  ,							_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				str | None = None		):




 """simple docstring"""







 key *= -1

 return encrypt(_lowerCAmelCase  ,							_lowerCAmelCase  ,							_lowerCAmelCase		)



def   lowerCAmelCase						(						_lowerCAmelCase							:				str  ,							_lowerCAmelCase							:				str | None = None		):




 """simple docstring"""







 UpperCAmelCase__								=  alphabet or ascii_letters

 # To store data on all the combinations
 UpperCAmelCase__								=  {}

 # Cycle through each combination
 for key in range(1  ,							len(_lowerCAmelCase		) + 1		):
  # Decrypt the message and store the result in the data
  UpperCAmelCase__								=  decrypt(_lowerCAmelCase  ,							_lowerCAmelCase  ,							_lowerCAmelCase		)

 return brute_force_data


if __name__ == "__main__":
  while True:
    print(F'''\n{"-" * 1_0}\n Menu\n{"-" * 1_0}''')
    print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n")

    # get user input
    _lowerCAmelCase  :				List[Any]						=				input("\nWhat would you like to do?: ").strip() or "4"

    # run functions based on what the user chose
    if choice not in ("1", "2", "3", "4"):
      print("Invalid choice, please enter a valid choice")
    elif choice == "1":
      _lowerCAmelCase  :				Any						=				input("Please enter the string to be encrypted: ")
      _lowerCAmelCase  :				str						=				int(input("Please enter off-set: ").strip())

      print(encrypt(input_string, key))
    elif choice == "2":
      _lowerCAmelCase  :				Optional[Any]						=				input("Please enter the string to be decrypted: ")
      _lowerCAmelCase  :				Any						=				int(input("Please enter off-set: ").strip())

      print(decrypt(input_string, key))
    elif choice == "3":
      _lowerCAmelCase  :				int						=				input("Please enter the string to be decrypted: ")
      _lowerCAmelCase  :				Dict						=				brute_force(input_string)

      for key, value in brute_force_data.items():
        print(F'''Key: {key} | Message: {value}''')

    elif choice == "4":
      print("Goodbye.")
      break





