from __future__ import annotations

import os
import tempfile
import unittest

from transformers import ConvBertConfig, 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 import (
        TFConvBertForMaskedLM,
        TFConvBertForMultipleChoice,
        TFConvBertForQuestionAnswering,
        TFConvBertForSequenceClassification,
        TFConvBertForTokenClassification,
        TFConvBertModel,
    )
class     a_			:






 '''simple docstring'''






 def __init__(      self :  Tuple      ,   lowercase__ :  Optional[Any]      ,   lowercase__ :  Dict=13      ,   lowercase__ :  Dict=7      ,   lowercase__ :  str=True      ,   lowercase__ :  str=True      ,   lowercase__ :  List[str]=True      ,   lowercase__ :  Dict=True      ,   lowercase__ :  Any=99      ,   lowercase__ :  Dict=32      ,   lowercase__ :  Optional[Any]=2      ,   lowercase__ :  Optional[int]=4      ,   lowercase__ :  Optional[int]=37      ,   lowercase__ :  Any="gelu"      ,   lowercase__ :  Any=0.1      ,   lowercase__ :  Tuple=0.1      ,   lowercase__ :  List[str]=512      ,   lowercase__ :  str=16      ,   lowercase__ :  Any=2      ,   lowercase__ :  Any=0.02      ,   lowercase__ :  List[Any]=3      ,   lowercase__ :  Dict=4      ,   lowercase__ :  Tuple=None      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = parent
        lowerCAmelCase__					     = 13
        lowerCAmelCase__					     = 7
        lowerCAmelCase__					     = True
        lowerCAmelCase__					     = True
        lowerCAmelCase__					     = True
        lowerCAmelCase__					     = True
        lowerCAmelCase__					     = 99
        lowerCAmelCase__					     = 384
        lowerCAmelCase__					     = 2
        lowerCAmelCase__					     = 4
        lowerCAmelCase__					     = 37
        lowerCAmelCase__					     = """gelu"""
        lowerCAmelCase__					     = 0.1
        lowerCAmelCase__					     = 0.1
        lowerCAmelCase__					     = 512
        lowerCAmelCase__					     = 16
        lowerCAmelCase__					     = 2
        lowerCAmelCase__					     = 0.02
        lowerCAmelCase__					     = 3
        lowerCAmelCase__					     = 4
        lowerCAmelCase__					     = 128
        lowerCAmelCase__					     = 2
        lowerCAmelCase__					     = 9
        lowerCAmelCase__					     = 1
        lowerCAmelCase__					     = None




 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        lowerCAmelCase__					     = ids_tensor([self.batch_size, self.seq_length]      ,   self.vocab_size)

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

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

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

        lowerCAmelCase__					     = ConvBertConfig(
            vocab_size=self.vocab_size      ,   hidden_size=self.hidden_size      ,   num_hidden_layers=self.num_hidden_layers      ,   num_attention_heads=self.num_attention_heads      ,   intermediate_size=self.intermediate_size      ,   hidden_act=self.hidden_act      ,   hidden_dropout_prob=self.hidden_dropout_prob      ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,   max_position_embeddings=self.max_position_embeddings      ,   type_vocab_size=self.type_vocab_size      ,   initializer_range=self.initializer_range      ,   return_dict=lowercase__      ,   )

        return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels




 def 		__snake_case						(      self :  str      ,   lowercase__ :  str      ,   lowercase__ :  Optional[int]      ,   lowercase__ :  List[Any]      ,   lowercase__ :  Union[str, Any]      ,   lowercase__ :  Any      ,   lowercase__ :  Union[str, Any]      ,   lowercase__ :  Tuple):







        '''simple docstring'''



        lowerCAmelCase__					     = TFConvBertModel(config=lowercase__)
        lowerCAmelCase__					     = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}

        lowerCAmelCase__					     = [input_ids, input_mask]
        lowerCAmelCase__					     = model(lowercase__)

        lowerCAmelCase__					     = model(lowercase__)

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




 def 		__snake_case						(      self :  Union[str, Any]      ,   lowercase__ :  str      ,   lowercase__ :  List[str]      ,   lowercase__ :  Dict      ,   lowercase__ :  Union[str, Any]      ,   lowercase__ :  Union[str, Any]      ,   lowercase__ :  Any      ,   lowercase__ :  Dict):







        '''simple docstring'''



        lowerCAmelCase__					     = TFConvBertForMaskedLM(config=lowercase__)
        lowerCAmelCase__					     = {
            """input_ids""": input_ids,
            """attention_mask""": input_mask,
            """token_type_ids""": token_type_ids,
        }
        lowerCAmelCase__					     = model(lowercase__)
        self.parent.assertEqual(result.logits.shape      ,   (self.batch_size, self.seq_length, self.vocab_size))




 def 		__snake_case						(      self :  Dict      ,   lowercase__ :  str      ,   lowercase__ :  Optional[Any]      ,   lowercase__ :  Tuple      ,   lowercase__ :  int      ,   lowercase__ :  Any      ,   lowercase__ :  str      ,   lowercase__ :  List[str]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.num_labels
        lowerCAmelCase__					     = TFConvBertForSequenceClassification(config=lowercase__)
        lowerCAmelCase__					     = {
            """input_ids""": input_ids,
            """attention_mask""": input_mask,
            """token_type_ids""": token_type_ids,
        }

        lowerCAmelCase__					     = model(lowercase__)
        self.parent.assertEqual(result.logits.shape      ,   (self.batch_size, self.num_labels))




 def 		__snake_case						(      self :  Tuple      ,   lowercase__ :  List[str]      ,   lowercase__ :  Dict      ,   lowercase__ :  List[str]      ,   lowercase__ :  Dict      ,   lowercase__ :  Optional[Any]      ,   lowercase__ :  Dict      ,   lowercase__ :  List[str]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.num_choices
        lowerCAmelCase__					     = TFConvBertForMultipleChoice(config=lowercase__)
        lowerCAmelCase__					     = tf.tile(tf.expand_dims(lowercase__      ,   1)      ,   (1, self.num_choices, 1))
        lowerCAmelCase__					     = tf.tile(tf.expand_dims(lowercase__      ,   1)      ,   (1, self.num_choices, 1))
        lowerCAmelCase__					     = tf.tile(tf.expand_dims(lowercase__      ,   1)      ,   (1, self.num_choices, 1))
        lowerCAmelCase__					     = {
            """input_ids""": multiple_choice_inputs_ids,
            """attention_mask""": multiple_choice_input_mask,
            """token_type_ids""": multiple_choice_token_type_ids,
        }
        lowerCAmelCase__					     = model(lowercase__)
        self.parent.assertEqual(result.logits.shape      ,   (self.batch_size, self.num_choices))




 def 		__snake_case						(      self :  Optional[int]      ,   lowercase__ :  Any      ,   lowercase__ :  str      ,   lowercase__ :  List[Any]      ,   lowercase__ :  Any      ,   lowercase__ :  int      ,   lowercase__ :  Optional[Any]      ,   lowercase__ :  Any):







        '''simple docstring'''



        lowerCAmelCase__					     = self.num_labels
        lowerCAmelCase__					     = TFConvBertForTokenClassification(config=lowercase__)
        lowerCAmelCase__					     = {
            """input_ids""": input_ids,
            """attention_mask""": input_mask,
            """token_type_ids""": token_type_ids,
        }
        lowerCAmelCase__					     = model(lowercase__)
        self.parent.assertEqual(result.logits.shape      ,   (self.batch_size, self.seq_length, self.num_labels))




 def 		__snake_case						(      self :  Union[str, Any]      ,   lowercase__ :  Optional[Any]      ,   lowercase__ :  Tuple      ,   lowercase__ :  Dict      ,   lowercase__ :  Union[str, Any]      ,   lowercase__ :  Optional[Any]      ,   lowercase__ :  int      ,   lowercase__ :  str):







        '''simple docstring'''



        lowerCAmelCase__					     = TFConvBertForQuestionAnswering(config=lowercase__)
        lowerCAmelCase__					     = {
            """input_ids""": input_ids,
            """attention_mask""": input_mask,
            """token_type_ids""": token_type_ids,
        }

        lowerCAmelCase__					     = model(lowercase__)
        self.parent.assertEqual(result.start_logits.shape      ,   (self.batch_size, self.seq_length))
        self.parent.assertEqual(result.end_logits.shape      ,   (self.batch_size, self.seq_length))




 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        lowerCAmelCase__					     = self.prepare_config_and_inputs()
        (
            lowerCAmelCase__						
        )					     = config_and_inputs
        lowerCAmelCase__					     = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
        return config, inputs_dict






@require_tf
class     a_			(						__UpperCamelCase	,					__UpperCamelCase	,					unittest.TestCase						):






 '''simple docstring'''






 UpperCAmelCase_     			= (
     (
         TFConvBertModel,
         TFConvBertForMaskedLM,
         TFConvBertForQuestionAnswering,
         TFConvBertForSequenceClassification,
         TFConvBertForTokenClassification,
         TFConvBertForMultipleChoice,
     )
     if is_tf_available()
     else ()
 )
 UpperCAmelCase_     			= (
     {
         """feature-extraction""": TFConvBertModel,
         """fill-mask""": TFConvBertForMaskedLM,
         """question-answering""": TFConvBertForQuestionAnswering,
         """text-classification""": TFConvBertForSequenceClassification,
         """token-classification""": TFConvBertForTokenClassification,
         """zero-shot""": TFConvBertForSequenceClassification,
     }
     if is_tf_available()
     else {}
 )
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False




 def 		__snake_case						(      self :  Any):







        '''simple docstring'''



        lowerCAmelCase__					     = TFConvBertModelTester(self)
        lowerCAmelCase__					     = ConfigTester(self      ,   config_class=lowercase__      ,   hidden_size=37)




 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        self.config_tester.run_common_tests()




 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase__)




 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_lm(*lowercase__)




 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_multiple_choice(*lowercase__)




 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(*lowercase__)




 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_sequence_classification(*lowercase__)




 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*lowercase__)




 @slow
 def 		__snake_case						(      self :  Optional[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase__					     = True
        lowerCAmelCase__					     = True

        if hasattr(lowercase__      ,   'use_cache'):
               lowerCAmelCase__					     = True

        lowerCAmelCase__					     = getattr(self.model_tester      ,   'encoder_seq_length'      ,   self.model_tester.seq_length)
        lowerCAmelCase__					     = getattr(self.model_tester      ,   'key_length'      ,   lowercase__)

        for model_class in self.all_model_classes:
               lowerCAmelCase__					     = self._prepare_for_class(lowercase__      ,   lowercase__)
               lowerCAmelCase__					     = model_class(lowercase__)
               lowerCAmelCase__					     = len(model(lowercase__))

               with tempfile.TemporaryDirectory() as tmpdirname:
                      model.save_pretrained(lowercase__      ,   saved_model=lowercase__)
                      lowerCAmelCase__					     = os.path.join(lowercase__      ,   'saved_model'      ,   '1')
                      lowerCAmelCase__					     = tf.keras.models.load_model(lowercase__)
                      lowerCAmelCase__					     = model(lowercase__)

                      if self.is_encoder_decoder:
                             lowerCAmelCase__					     = outputs["""encoder_hidden_states"""]
                             lowerCAmelCase__					     = outputs["""encoder_attentions"""]
                      else:
                             lowerCAmelCase__					     = outputs["""hidden_states"""]
                             lowerCAmelCase__					     = outputs["""attentions"""]

                      self.assertEqual(len(lowercase__)      ,   lowercase__)

                      lowerCAmelCase__					     = getattr(
                          self.model_tester      ,   'expected_num_hidden_layers'      ,   self.model_tester.num_hidden_layers + 1)

                      self.assertEqual(len(lowercase__)      ,   lowercase__)
                      self.assertListEqual(
                          list(output_hidden_states[0].shape[-2:])      ,   [self.model_tester.seq_length, self.model_tester.hidden_size]      ,   )

                      self.assertEqual(len(lowercase__)      ,   self.model_tester.num_hidden_layers)
                      self.assertListEqual(
                          list(output_attentions[0].shape[-3:])      ,   [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length]      ,   )




 @slow
 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        lowerCAmelCase__					     = TFConvBertModel.from_pretrained('YituTech/conv-bert-base')
        self.assertIsNotNone(lowercase__)




 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()
        lowerCAmelCase__					     = True
        lowerCAmelCase__					     = getattr(self.model_tester      ,   'decoder_seq_length'      ,   self.model_tester.seq_length)
        lowerCAmelCase__					     = getattr(self.model_tester      ,   'encoder_seq_length'      ,   self.model_tester.seq_length)
        lowerCAmelCase__					     = getattr(self.model_tester      ,   'key_length'      ,   lowercase__)
        lowerCAmelCase__					     = getattr(self.model_tester      ,   'key_length'      ,   lowercase__)

        def check_decoder_attentions_output(lowercase__ :  Optional[Any]):
               lowerCAmelCase__					     = len(lowercase__)
               self.assertEqual(out_len % 2      ,   0)
               lowerCAmelCase__					     = outputs.decoder_attentions
               self.assertEqual(len(lowercase__)      ,   self.model_tester.num_hidden_layers)
               self.assertListEqual(
                   list(decoder_attentions[0].shape[-3:])      ,   [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length]      ,   )

        def check_encoder_attentions_output(lowercase__ :  Optional[int]):
               lowerCAmelCase__					     = [
                   t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions)
               ]
               self.assertEqual(len(lowercase__)      ,   self.model_tester.num_hidden_layers)
               self.assertListEqual(
                   list(attentions[0].shape[-3:])      ,   [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length]      ,   )

        for model_class in self.all_model_classes:
               lowerCAmelCase__					     = True
               lowerCAmelCase__					     = False
               lowerCAmelCase__					     = model_class(lowercase__)
               lowerCAmelCase__					     = model(self._prepare_for_class(lowercase__      ,   lowercase__))
               lowerCAmelCase__					     = len(lowercase__)
               self.assertEqual(config.output_hidden_states      ,   lowercase__)
               check_encoder_attentions_output(lowercase__)

               if self.is_encoder_decoder:
                      lowerCAmelCase__					     = model_class(lowercase__)
                      lowerCAmelCase__					     = model(self._prepare_for_class(lowercase__      ,   lowercase__))
                      self.assertEqual(config.output_hidden_states      ,   lowercase__)
                      check_decoder_attentions_output(lowercase__)

               # Check that output attentions can also be changed via the config
               del inputs_dict["output_attentions"]
               lowerCAmelCase__					     = True
               lowerCAmelCase__					     = model_class(lowercase__)
               lowerCAmelCase__					     = model(self._prepare_for_class(lowercase__      ,   lowercase__))
               self.assertEqual(config.output_hidden_states      ,   lowercase__)
               check_encoder_attentions_output(lowercase__)

               # Check attention is always last and order is fine
               lowerCAmelCase__					     = True
               lowerCAmelCase__					     = True
               lowerCAmelCase__					     = model_class(lowercase__)
               lowerCAmelCase__					     = model(self._prepare_for_class(lowercase__      ,   lowercase__))

               self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1)      ,   len(lowercase__))
               self.assertEqual(model.config.output_hidden_states      ,   lowercase__)
               check_encoder_attentions_output(lowercase__)






@require_tf
class     a_			(						unittest.TestCase						):






 '''simple docstring'''






 @slow
 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = TFConvBertModel.from_pretrained('YituTech/conv-bert-base')
        lowerCAmelCase__					     = tf.constant([[0, 1, 2, 3, 4, 5]])
        lowerCAmelCase__					     = model(lowercase__)[0]

        lowerCAmelCase__					     = [1, 6, 768]
        self.assertEqual(output.shape      ,   lowercase__)

        lowerCAmelCase__					     = tf.constant(
            [
                [
                    [-0.03_475_493, -0.4_686_034, -0.30_638_832],
                    [0.22_637_248, -0.26_988_646, -0.7_423_424],
                    [0.10_324_868, -0.45_013_508, -0.58_280_784],
                ]
            ])
        tf.debugging.assert_near(output[:, :3, :3]      ,   lowercase__      ,   atol=1e-4)

from __future__ import annotations

lowerCAmelCase__     						=			tuple[int, int, int]
lowerCAmelCase__     						=			tuple[str, str, str]


# used alphabet --------------------------
# from string.ascii_uppercase
lowerCAmelCase__     						=			'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

# -------------------------- default selection --------------------------
# rotors --------------------------
lowerCAmelCase__     						=			'EGZWVONAHDCLFQMSIPJBYUKXTR'
lowerCAmelCase__     						=			'FOBHMDKEXQNRAULPGSJVTYICZW'
lowerCAmelCase__     						=			'ZJXESIUQLHAVRMDOYGTNFWPBKC'
# reflector --------------------------
lowerCAmelCase__     						=			{
    'A': 'N',
    'N': 'A',
    'B': 'O',
    'O': 'B',
    'C': 'P',
    'P': 'C',
    'D': 'Q',
    'Q': 'D',
    'E': 'R',
    'R': 'E',
    'F': 'S',
    'S': 'F',
    'G': 'T',
    'T': 'G',
    'H': 'U',
    'U': 'H',
    'I': 'V',
    'V': 'I',
    'J': 'W',
    'W': 'J',
    'K': 'X',
    'X': 'K',
    'L': 'Y',
    'Y': 'L',
    'M': 'Z',
    'Z': 'M',
}

# -------------------------- extra rotors --------------------------
lowerCAmelCase__     						=			'RMDJXFUWGISLHVTCQNKYPBEZOA'
lowerCAmelCase__     						=			'SGLCPQWZHKXAREONTFBVIYJUDM'
lowerCAmelCase__     						=			'HVSICLTYKQUBXDWAJZOMFGPREN'
lowerCAmelCase__     						=			'RZWQHFMVDBKICJLNTUXAGYPSOE'
lowerCAmelCase__     						=			'LFKIJODBEGAMQPXVUHYSTCZRWN'
lowerCAmelCase__     						=			'KOAEGVDHXPQZMLFTYWJNBRCIUS'






def 				__lowerCamelCase		(						lowerCAmelCase__     ,  lowerCAmelCase__     ,  lowerCAmelCase__     ):
       # Checks if there are 3 unique rotors

       if (unique_rotsel := len(set(lowerCAmelCase__     )     )) < 3:
              lowerCAmelCase__					     = F"""Please use 3 unique rotors (not {unique_rotsel})"""
              raise Exception(lowerCAmelCase__     )

       # Checks if rotor positions are valid
       lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__					     = rotpos
       if not 0 < rotorposa <= len(lowerCAmelCase__     ):
              lowerCAmelCase__					     = F"""First rotor position is not within range of 1..26 ({rotorposa}"""
              raise ValueError(lowerCAmelCase__     )
       if not 0 < rotorposa <= len(lowerCAmelCase__     ):
              lowerCAmelCase__					     = F"""Second rotor position is not within range of 1..26 ({rotorposa})"""
              raise ValueError(lowerCAmelCase__     )
       if not 0 < rotorposa <= len(lowerCAmelCase__     ):
              lowerCAmelCase__					     = F"""Third rotor position is not within range of 1..26 ({rotorposa})"""
              raise ValueError(lowerCAmelCase__     )

       # Validates string and returns dict
       lowerCAmelCase__					     = _plugboard(lowerCAmelCase__     )

       return rotpos, rotsel, pbdict






def 				__lowerCamelCase		(						lowerCAmelCase__     ):

       # tests the input string if it
       # a) is type string
       # b) has even length (so pairs can be made)
       if not isinstance(lowerCAmelCase__     ,  lowerCAmelCase__     ):
              lowerCAmelCase__					     = F"""Plugboard setting isn't type string ({type(lowerCAmelCase__     )})"""
              raise TypeError(lowerCAmelCase__     )
       elif len(lowerCAmelCase__     ) % 2 != 0:
              lowerCAmelCase__					     = F"""Odd number of symbols ({len(lowerCAmelCase__     )})"""
              raise Exception(lowerCAmelCase__     )
       elif pbstring == "":
              return {}

       pbstring.replace(' '     ,  ''     )

       # Checks if all characters are unique
       lowerCAmelCase__					     = set()
       for i in pbstring:
              if i not in abc:
                     lowerCAmelCase__					     = F"""'{i}' not in list of symbols"""
                     raise Exception(lowerCAmelCase__     )
              elif i in tmppbl:
                     lowerCAmelCase__					     = F"""Duplicate symbol ({i})"""
                     raise Exception(lowerCAmelCase__     )
              else:
                     tmppbl.add(lowerCAmelCase__     )
       del tmppbl

       # Created the dictionary
       lowerCAmelCase__					     = {}
       for j in range(0     ,  len(lowerCAmelCase__     ) - 1     ,  2     ):
              lowerCAmelCase__					     = pbstring[j + 1]
              lowerCAmelCase__					     = pbstring[j]

       return pb






def 				__lowerCamelCase		(						lowerCAmelCase__     ,  lowerCAmelCase__     ,  lowerCAmelCase__ = (rotora, rotora, rotora)     ,  lowerCAmelCase__ = ""     ,  ):
       lowerCAmelCase__					     = text.upper()
       lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__					     = _validator(
           lowerCAmelCase__     ,  lowerCAmelCase__     ,  plugb.upper()     )

       lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__					     = rotor_position
       lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__					     = rotor_selection
       rotorposa -= 1
       rotorposa -= 1
       rotorposa -= 1

       lowerCAmelCase__					     = []

       # encryption/decryption process --------------------------
       for symbol in text:
              if symbol in abc:
                     # 1st plugboard --------------------------
                     if symbol in plugboard:
                            lowerCAmelCase__					     = plugboard[symbol]

                     # rotor ra --------------------------
                     lowerCAmelCase__					     = abc.index(lowerCAmelCase__     ) + rotorposa
                     lowerCAmelCase__					     = rotora[index % len(lowerCAmelCase__     )]

                     # rotor rb --------------------------
                     lowerCAmelCase__					     = abc.index(lowerCAmelCase__     ) + rotorposa
                     lowerCAmelCase__					     = rotora[index % len(lowerCAmelCase__     )]

                     # rotor rc --------------------------
                     lowerCAmelCase__					     = abc.index(lowerCAmelCase__     ) + rotorposa
                     lowerCAmelCase__					     = rotora[index % len(lowerCAmelCase__     )]

                     # reflector --------------------------
                     # this is the reason you don't need another machine to decipher

                     lowerCAmelCase__					     = reflector[symbol]

                     # 2nd rotors
                     lowerCAmelCase__					     = abc[rotora.index(lowerCAmelCase__     ) - rotorposa]
                     lowerCAmelCase__					     = abc[rotora.index(lowerCAmelCase__     ) - rotorposa]
                     lowerCAmelCase__					     = abc[rotora.index(lowerCAmelCase__     ) - rotorposa]

                     # 2nd plugboard
                     if symbol in plugboard:
                            lowerCAmelCase__					     = plugboard[symbol]

                     # moves/resets rotor positions
                     rotorposa += 1
                     if rotorposa >= len(lowerCAmelCase__     ):
                            lowerCAmelCase__					     = 0
                            rotorposa += 1
                     if rotorposa >= len(lowerCAmelCase__     ):
                            lowerCAmelCase__					     = 0
                            rotorposa += 1
                     if rotorposa >= len(lowerCAmelCase__     ):
                            lowerCAmelCase__					     = 0

        # else:
        #    pass
        #    Error could be also raised
        #    raise ValueError(
        #       'Invalid symbol('+repr(symbol)+')')
              result.append(lowerCAmelCase__     )

       return "".join(lowerCAmelCase__     )


if __name__ == "__main__":
    lowerCAmelCase__     						=			'This is my Python script that emulates the Enigma machine from WWII.'
    lowerCAmelCase__     						=			(1, 1, 1)
    lowerCAmelCase__     						=			'pictures'
    lowerCAmelCase__     						=			(rotora, rotora, rotora)
    lowerCAmelCase__     						=			enigma(message, rotor_pos, rotor_sel, pb)

    print('Encrypted message:', en)
    print('Decrypted message:', enigma(en, rotor_pos, rotor_sel, pb))
