

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 						lowercase_					(						__lowercase  ):



      def __init__(    self   :       Dict    ,      A__   :       int    ,      )					->  List[str]:
        _snake_case		=							parent
        _snake_case		=							13
        _snake_case		=							7
        _snake_case		=							True
        _snake_case		=							True
        _snake_case		=							True
        _snake_case		=							True
        _snake_case		=							True
        _snake_case		=							99
        _snake_case		=							32
        _snake_case		=							2
        _snake_case		=							4
        _snake_case		=							37
        _snake_case		=							'''gelu'''
        _snake_case		=							0.1
        _snake_case		=							0.1
        _snake_case		=							512
        _snake_case		=							16
        _snake_case		=							2
        _snake_case		=							0.02
        _snake_case		=							3
        _snake_case		=							4
        _snake_case		=							None
        _snake_case		=							self.vocab_size - 1



      def 		UpperCamelCase_	(    self   :       List[Any]	)					->  Tuple:
        _snake_case		=							ids_tensor([self.batch_size, self.seq_length]    ,      self.vocab_size	)

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

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

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

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

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

        _snake_case		=							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   :       Any    ,      A__   :       Union[str, Any]    ,      A__   :       Union[str, Any]    ,      A__   :       Optional[int]    ,      A__   :       Any    ,      A__   :       Optional[Any]    ,      *A__   :       Tuple	)					->  Optional[int]:
        _snake_case		=							TFCTRLModel(config=A__	)
        _snake_case		=							{'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
        _snake_case		=							model(A__	)

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

        _snake_case		=							model(A__	)

        self.parent.assertEqual(result.last_hidden_state.shape    ,      (self.batch_size, self.seq_length, self.hidden_size)	)



      def 		UpperCamelCase_	(    self   :       Optional[Any]    ,      A__   :       Any    ,      A__   :       List[str]    ,      A__   :       Optional[Any]    ,      A__   :       List[Any]    ,      A__   :       str    ,      *A__   :       Optional[int]	)					->  Tuple:
        _snake_case		=							TFCTRLLMHeadModel(config=A__	)
        _snake_case		=							{'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
        _snake_case		=							model(A__	)
        self.parent.assertEqual(result.logits.shape    ,      (self.batch_size, self.seq_length, self.vocab_size)	)



      def 		UpperCamelCase_	(    self   :       List[str]    ,      A__   :       Tuple    ,      A__   :       int    ,      A__   :       List[Any]    ,      A__   :       Any    ,      A__   :       Dict    ,      *A__   :       Optional[int]	)					->  str:
        _snake_case		=							self.num_labels
        _snake_case		=							ids_tensor([self.batch_size]    ,      self.type_sequence_label_size	)
        _snake_case		=							{
            '''input_ids''': input_ids,
            '''token_type_ids''': token_type_ids,
            '''labels''': sequence_labels,
        }
        _snake_case		=							TFCTRLForSequenceClassification(A__	)
        _snake_case		=							model(A__	)
        self.parent.assertEqual(result.logits.shape    ,      (self.batch_size, self.num_labels)	)







      def 		UpperCamelCase_	(    self   :       Any	)					->  str:
        _snake_case		=							self.prepare_config_and_inputs()

        (
            (
            _snake_case  
        ),  (
            _snake_case  
        ),  (
            _snake_case  
        ),  (
            _snake_case  
        ),  (
            _snake_case  
        ),  (
            _snake_case  
        ),  (
            _snake_case  
        ),  (
            _snake_case  
        ),  (
            _snake_case  
        ),    
        )		=							config_and_inputs

        _snake_case		=							{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
        return config, inputs_dict



@require_tf
class 						lowercase_					(						__lowercase     ,							__lowercase     ,							unittest.TestCase  ):
      UpperCamelCase_    :	List[Any]		   =       (TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
      UpperCamelCase_    :	int		   =       (TFCTRLLMHeadModel,) if is_tf_available() else ()
      UpperCamelCase_    :	List[Any]		   =       (
          {
              "feature-extraction": TFCTRLModel,
              "text-classification": TFCTRLForSequenceClassification,
              "text-generation": TFCTRLLMHeadModel,
              "zero-shot": TFCTRLForSequenceClassification,
          }
          if is_tf_available()
          else {}
      )
      UpperCamelCase_    :	Dict		   =       False
      UpperCamelCase_    :	Union[str, Any]		   =       False



      def 		UpperCamelCase_	(    self   :       int    ,      A__   :       Optional[int]    ,      A__   :       List[Any]    ,      A__   :       Optional[int]    ,      A__   :       List[str]    ,      A__   :       List[str]	)					->  Optional[int]:
        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	)					->  Dict:
        _snake_case		=							TFCTRLModelTester(self	)
        _snake_case		=							ConfigTester(self    ,      config_class=A__    ,      n_embd=37	)



      def 		UpperCamelCase_	(    self   :       List[Any]	)					->  Tuple:
        self.config_tester.run_common_tests()



      def 		UpperCamelCase_	(    self   :       Any	)					->  int:
        _snake_case		=							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_ctrl_model(*A__	)



      def 		UpperCamelCase_	(    self   :       Union[str, Any]	)					->  int:
        _snake_case		=							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_ctrl_lm_head(*A__	)



      def 		UpperCamelCase_	(    self   :       Tuple	)					->  Union[str, Any]:
        _snake_case		=							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_ctrl_for_sequence_classification(*A__	)



      def 		UpperCamelCase_	(    self   :       Dict	)					->  Optional[int]:
        _snake_case,  _snake_case		=							self.model_tester.prepare_config_and_inputs_for_common()
        _snake_case		=							[TFCTRLLMHeadModel]
        _snake_case		=							[TFCTRLForSequenceClassification]

        for model_class in self.all_model_classes:
          _snake_case		=							model_class(A__	)
          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:
            _snake_case		=							model.get_output_embeddings()
            assert isinstance(A__    ,      tf.keras.layers.Layer	)
            _snake_case		=							model.get_bias()
            assert isinstance(A__    ,      A__	)
            for k, v in name.items():
              assert isinstance(A__    ,      tf.Variable	)
          elif model_class in list_other_models_with_output_ebd:
            _snake_case		=							model.get_output_embeddings()
            assert isinstance(A__    ,      tf.keras.layers.Layer	)
            _snake_case		=							model.get_bias()
            assert name is None
          else:
            _snake_case		=							model.get_output_embeddings()
            assert x is None
            _snake_case		=							model.get_bias()
            assert name is None







      @slow
      def 		UpperCamelCase_	(    self   :       str	)					->  Union[str, Any]:
        for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          _snake_case		=							TFCTRLModel.from_pretrained(A__	)
          self.assertIsNotNone(A__	)



@require_tf
class 						lowercase_					(						unittest.TestCase  ):



      @slow
      def 		UpperCamelCase_	(    self   :       Tuple	)					->  Dict:
        _snake_case		=							TFCTRLLMHeadModel.from_pretrained('''ctrl'''	)
        _snake_case		=							tf.convert_to_tensor([[11859, 0, 1611, 8]]    ,      dtype=tf.intaa	)  # Legal the president is
        _snake_case		=							[
            11859,
            0,
            1611,
            8,
            5,
            150,
            26449,
            2,
            19,
            348,
            469,
            3,
            2595,
            48,
            20740,
            246533,
            246533,
            19,
            30,
            5,
        ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

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




import random
import sys

from . import cryptomath_module as cryptomath

__A    	=			(
    r''' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`'''
    r'''abcdefghijklmnopqrstuvwxyz{|}~'''
)



def    snake_case_(_UpperCamelCase				, _UpperCamelCase				, _UpperCamelCase  )							->			None:



  """simple docstring"""






  if mode == "encrypt":
    if key_a == 1:
      sys.exit(
          '''The affine cipher becomes weak when key '''
          '''A is set to 1. Choose different key'''  )
    if key_b == 0:
      sys.exit(
          '''The affine cipher becomes weak when key '''
          '''B is set to 0. Choose different key'''  )
  if key_a < 0 or key_b < 0 or key_b > len(_UpperCamelCase  ) - 1:
    sys.exit(
        '''Key A must be greater than 0 and key B must '''
        F"""be between 0 and {len(_UpperCamelCase  ) - 1}."""  )
  if cryptomath.gcd(_UpperCamelCase				, len(_UpperCamelCase  )  ) != 1:
    sys.exit(
        F"""Key A {key_a} and the symbol set size {len(_UpperCamelCase  )} """
        '''are not relatively prime. Choose a different key.'''  )



def    snake_case_(_UpperCamelCase				, _UpperCamelCase  )							->			str:



  """simple docstring"""






  _snake_case,  _snake_case		=							divmod(_UpperCamelCase				, len(_UpperCamelCase  )  )
  check_keys(_UpperCamelCase				, _UpperCamelCase				, '''encrypt'''  )
  _snake_case		=							''''''
  for symbol in message:
    if symbol in SYMBOLS:
      _snake_case		=							SYMBOLS.find(_UpperCamelCase  )
      cipher_text += SYMBOLS[(sym_index * key_a + key_b) % len(_UpperCamelCase  )]
    else:
      cipher_text += symbol
  return cipher_text



def    snake_case_(_UpperCamelCase				, _UpperCamelCase  )							->			str:



  """simple docstring"""






  _snake_case,  _snake_case		=							divmod(_UpperCamelCase				, len(_UpperCamelCase  )  )
  check_keys(_UpperCamelCase				, _UpperCamelCase				, '''decrypt'''  )
  _snake_case		=							''''''
  _snake_case		=							cryptomath.find_mod_inverse(_UpperCamelCase				, len(_UpperCamelCase  )  )
  for symbol in message:
    if symbol in SYMBOLS:
      _snake_case		=							SYMBOLS.find(_UpperCamelCase  )
      plain_text += SYMBOLS[
          (sym_index - key_b) * mod_inverse_of_key_a % len(_UpperCamelCase  )
      ]
    else:
      plain_text += symbol
  return plain_text



def    snake_case_()							->			int:



  """simple docstring"""






  while True:
    _snake_case		=							random.randint(2				, len(_UpperCamelCase  )  )
    _snake_case		=							random.randint(2				, len(_UpperCamelCase  )  )
    if cryptomath.gcd(_UpperCamelCase				, len(_UpperCamelCase  )  ) == 1 and key_b % len(_UpperCamelCase  ) != 0:
      return key_b * len(_UpperCamelCase  ) + key_b



def    snake_case_()							->			None:



  """simple docstring"""






  _snake_case		=							input('''Enter message: '''  ).strip()
  _snake_case		=							int(input('''Enter key [2000 - 9000]: '''  ).strip()  )
  _snake_case		=							input('''Encrypt/Decrypt [E/D]: '''  ).strip().lower()

  if mode.startswith('''e'''  ):
    _snake_case		=							'''encrypt'''
    _snake_case		=							encrypt_message(_UpperCamelCase				, _UpperCamelCase  )
  elif mode.startswith('''d'''  ):
    _snake_case		=							'''decrypt'''
    _snake_case		=							decrypt_message(_UpperCamelCase				, _UpperCamelCase  )
  print(F"""\n{mode.title()}ed text: \n{translated}"""  )


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 # main()

