





"""simple docstring"""




import logging

import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.albert.modeling_albert import (
    ALBERT_INPUTS_DOCSTRING,
    ALBERT_START_DOCSTRING,
    AlbertModel,
    AlbertPreTrainedModel,
    AlbertTransformer,
)


UpperCamelCase_           =logging.getLogger(__name__)




class  _a						(      _lowerCAmelCase				):






				def 				snake_case	( self		:    int, lowerCAmelCase__		:    List[Any], lowerCAmelCase__		:    Tuple, lowerCAmelCase__		:    str=None, lowerCAmelCase__		:    Any=None							)	->      Union[str, Any]:




										'''simple docstring'''



										if current_layer == 0:
																_UpperCamelCase			:					Any     =    self.embedding_hidden_mapping_in(lowerCAmelCase__							)
										else:
																_UpperCamelCase			:					Any     =    hidden_states[0]

										_UpperCamelCase			:					str     =    int(self.config.num_hidden_layers / self.config.num_hidden_groups							)

										# Index of the hidden group
										_UpperCamelCase			:					Any     =    int(current_layer / (self.config.num_hidden_layers / self.config.num_hidden_groups)							)

										_UpperCamelCase			:					List[str]     =    self.albert_layer_groups[group_idx](
										    lowerCAmelCase__, lowerCAmelCase__, head_mask[group_idx * layers_per_group : (group_idx + 1) * layers_per_group], )
										_UpperCamelCase			:					Dict     =    layer_group_output[0]

										return (hidden_states,)




@add_start_docstrings(
    '''The bare ALBERT Model transformer with PABEE outputting raw hidden-states without any specific head on top.'''	,				_lowerCAmelCase	,				)
class  _a						(      _lowerCAmelCase				):






				def __init__( self		:    str, lowerCAmelCase__		:    int							)	->      List[str]:




										'''simple docstring'''



										super().__init__(lowerCAmelCase__							)

										_UpperCamelCase			:					str     =    AlbertTransformerWithPabee(lowerCAmelCase__							)

										self.init_weights()
										_UpperCamelCase			:					Optional[Any]     =    0
										_UpperCamelCase			:					Any     =    0
										_UpperCamelCase			:					str     =    0

										_UpperCamelCase			:					Optional[int]     =    0






				def 				snake_case	( self		:    str, lowerCAmelCase__		:    Optional[int]							)	->      List[str]:




										'''simple docstring'''



										_UpperCamelCase			:					str     =    threshold






				def 				snake_case	( self		:    List[Any], lowerCAmelCase__		:    Optional[Any]							)	->      Dict:




										'''simple docstring'''



										_UpperCamelCase			:					Optional[Any]     =    patience






				def 				snake_case	( self		:    Optional[int]							)	->      Dict:




										'''simple docstring'''



										_UpperCamelCase			:					Any     =    0
										_UpperCamelCase			:					Optional[Any]     =    0






				def 				snake_case	( self		:    Tuple							)	->      List[str]:




										'''simple docstring'''



										_UpperCamelCase			:					Optional[int]     =    self.inference_layers_num / self.inference_instances_num
										_UpperCamelCase			:					Any     =    (
										    f"""*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up ="""
										    f""" {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***"""
										)
										print(lowerCAmelCase__							)






				@add_start_docstrings_to_model_forward(lowerCAmelCase__							)
				def 				snake_case	( self		:    Dict, lowerCAmelCase__		:    Union[str, Any]=None, lowerCAmelCase__		:    List[Any]=None, lowerCAmelCase__		:    str=None, lowerCAmelCase__		:    str=None, lowerCAmelCase__		:    Union[str, Any]=None, lowerCAmelCase__		:    List[str]=None, lowerCAmelCase__		:    Optional[Any]=None, lowerCAmelCase__		:    str=None, lowerCAmelCase__		:    Dict=False, )	->      Optional[Any]:




										'''simple docstring'''



										if input_ids is not None and inputs_embeds is not None:
																raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time'''							)
										elif input_ids is not None:
																_UpperCamelCase			:					str     =    input_ids.size()
										elif inputs_embeds is not None:
																_UpperCamelCase			:					Union[str, Any]     =    inputs_embeds.size()[:-1]
										else:
																raise ValueError('''You have to specify either input_ids or inputs_embeds'''							)

										_UpperCamelCase			:					Optional[int]     =    input_ids.device if input_ids is not None else inputs_embeds.device

										if attention_mask is None:
																_UpperCamelCase			:					Optional[Any]     =    torch.ones(lowerCAmelCase__, device=lowerCAmelCase__							)
										if token_type_ids is None:
																_UpperCamelCase			:					str     =    torch.zeros(lowerCAmelCase__, dtype=torch.long, device=lowerCAmelCase__							)

										_UpperCamelCase			:					List[str]     =    attention_mask.unsqueeze(1							).unsqueeze(2							)
										_UpperCamelCase			:					Tuple     =    extended_attention_mask.to(dtype=self.dtype							)  # fp16 compatibility
										_UpperCamelCase			:					Any     =    (1.0 - extended_attention_mask) * -10_000.0
										_UpperCamelCase			:					Optional[int]     =    self.get_head_mask(lowerCAmelCase__, self.config.num_hidden_layers							)

										_UpperCamelCase			:					List[str]     =    self.embeddings(
										    lowerCAmelCase__, position_ids=lowerCAmelCase__, token_type_ids=lowerCAmelCase__, inputs_embeds=lowerCAmelCase__							)
										_UpperCamelCase			:					List[Any]     =    embedding_output

										if self.training:
																_UpperCamelCase			:					Dict     =    []
																for i in range(self.config.num_hidden_layers							):
																						_UpperCamelCase			:					List[str]     =    self.encoder.adaptive_forward(
																						    lowerCAmelCase__, current_layer=lowerCAmelCase__, attention_mask=lowerCAmelCase__, head_mask=lowerCAmelCase__, )

																						_UpperCamelCase			:					Union[str, Any]     =    self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]							)							)
																						_UpperCamelCase			:					Any     =    output_layers[i](output_dropout(lowerCAmelCase__							)							)
																						res.append(lowerCAmelCase__							)
										elif self.patience == 0:  # Use all layers for inference
																_UpperCamelCase			:					Optional[int]     =    self.encoder(lowerCAmelCase__, lowerCAmelCase__, head_mask=lowerCAmelCase__							)
																_UpperCamelCase			:					str     =    self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]							)							)
																_UpperCamelCase			:					Tuple     =    [output_layers[self.config.num_hidden_layers - 1](lowerCAmelCase__							)]
										else:
																_UpperCamelCase			:					Optional[Any]     =    0
																_UpperCamelCase			:					List[Any]     =    None
																_UpperCamelCase			:					Optional[int]     =    0
																for i in range(self.config.num_hidden_layers							):
																						calculated_layer_num += 1
																						_UpperCamelCase			:					Dict     =    self.encoder.adaptive_forward(
																						    lowerCAmelCase__, current_layer=lowerCAmelCase__, attention_mask=lowerCAmelCase__, head_mask=lowerCAmelCase__, )

																						_UpperCamelCase			:					List[Any]     =    self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]							)							)
																						_UpperCamelCase			:					int     =    output_layers[i](lowerCAmelCase__							)
																						if regression:
																												_UpperCamelCase			:					List[str]     =    logits.detach()
																												if patient_result is not None:
																																		_UpperCamelCase			:					Any     =    patient_result.detach()
																												if (patient_result is not None) and torch.abs(patient_result - labels							) < self.regression_threshold:
																																		patient_counter += 1
																												else:
																																		_UpperCamelCase			:					Dict     =    0
																						else:
																												_UpperCamelCase			:					Union[str, Any]     =    logits.detach().argmax(dim=1							)
																												if patient_result is not None:
																																		_UpperCamelCase			:					int     =    patient_result.detach().argmax(dim=1							)
																												if (patient_result is not None) and torch.all(labels.eq(lowerCAmelCase__							)							):
																																		patient_counter += 1
																												else:
																																		_UpperCamelCase			:					Union[str, Any]     =    0

																						_UpperCamelCase			:					List[str]     =    logits
																						if patient_counter == self.patience:
																												break
																_UpperCamelCase			:					Tuple     =    [patient_result]
																self.inference_layers_num += calculated_layer_num
																self.inference_instances_num += 1

										return res




@add_start_docstrings(
    '''Albert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of
    the pooled output) e.g. for GLUE tasks. '''	,				_lowerCAmelCase	,				)
class  _a						(      _lowerCAmelCase				):






				def __init__( self		:    Optional[Any], lowerCAmelCase__		:    int							)	->      List[str]:




										'''simple docstring'''



										super().__init__(lowerCAmelCase__							)
										_UpperCamelCase			:					Dict     =    config.num_labels

										_UpperCamelCase			:					Optional[Any]     =    AlbertModelWithPabee(lowerCAmelCase__							)
										_UpperCamelCase			:					List[Any]     =    nn.Dropout(config.classifier_dropout_prob							)
										_UpperCamelCase			:					Any     =    nn.ModuleList(
										    [nn.Linear(config.hidden_size, self.config.num_labels							) for _ in range(config.num_hidden_layers							)]							)

										self.init_weights()






				@add_start_docstrings_to_model_forward(lowerCAmelCase__							)
				def 				snake_case	( self		:    int, lowerCAmelCase__		:    str=None, lowerCAmelCase__		:    Any=None, lowerCAmelCase__		:    str=None, lowerCAmelCase__		:    Optional[int]=None, lowerCAmelCase__		:    List[Any]=None, lowerCAmelCase__		:    Union[str, Any]=None, lowerCAmelCase__		:    Optional[Any]=None, )	->      int:




										'''simple docstring'''



										_UpperCamelCase			:					List[str]     =    self.albert(
										    input_ids=lowerCAmelCase__, attention_mask=lowerCAmelCase__, token_type_ids=lowerCAmelCase__, position_ids=lowerCAmelCase__, head_mask=lowerCAmelCase__, inputs_embeds=lowerCAmelCase__, output_dropout=self.dropout, output_layers=self.classifiers, regression=self.num_labels == 1, )

										_UpperCamelCase			:					Optional[Any]     =    (logits[-1],)

										if labels is not None:
																_UpperCamelCase			:					Optional[Any]     =    None
																_UpperCamelCase			:					int     =    0
																for ix, logits_item in enumerate(lowerCAmelCase__							):
																						if self.num_labels == 1:
																												#  We are doing regression
																												_UpperCamelCase			:					Union[str, Any]     =    MSELoss()
																												_UpperCamelCase			:					str     =    loss_fct(logits_item.view(-1							), labels.view(-1							)							)
																						else:
																												_UpperCamelCase			:					Tuple     =    CrossEntropyLoss()
																												_UpperCamelCase			:					Any     =    loss_fct(logits_item.view(-1, self.num_labels							), labels.view(-1							)							)
																						if total_loss is None:
																												_UpperCamelCase			:					Union[str, Any]     =    loss
																						else:
																												total_loss += loss * (ix + 1)
																						total_weights += ix + 1
																_UpperCamelCase			:					str     =    (total_loss / total_weights,) + outputs

										return outputs










"""simple docstring"""




UpperCamelCase_           ={
    """A""": ("""ABCDEFGHIJKLM""", """NOPQRSTUVWXYZ"""),
    """B""": ("""ABCDEFGHIJKLM""", """NOPQRSTUVWXYZ"""),
    """C""": ("""ABCDEFGHIJKLM""", """ZNOPQRSTUVWXY"""),
    """D""": ("""ABCDEFGHIJKLM""", """ZNOPQRSTUVWXY"""),
    """E""": ("""ABCDEFGHIJKLM""", """YZNOPQRSTUVWX"""),
    """F""": ("""ABCDEFGHIJKLM""", """YZNOPQRSTUVWX"""),
    """G""": ("""ABCDEFGHIJKLM""", """XYZNOPQRSTUVW"""),
    """H""": ("""ABCDEFGHIJKLM""", """XYZNOPQRSTUVW"""),
    """I""": ("""ABCDEFGHIJKLM""", """WXYZNOPQRSTUV"""),
    """J""": ("""ABCDEFGHIJKLM""", """WXYZNOPQRSTUV"""),
    """K""": ("""ABCDEFGHIJKLM""", """VWXYZNOPQRSTU"""),
    """L""": ("""ABCDEFGHIJKLM""", """VWXYZNOPQRSTU"""),
    """M""": ("""ABCDEFGHIJKLM""", """UVWXYZNOPQRST"""),
    """N""": ("""ABCDEFGHIJKLM""", """UVWXYZNOPQRST"""),
    """O""": ("""ABCDEFGHIJKLM""", """TUVWXYZNOPQRS"""),
    """P""": ("""ABCDEFGHIJKLM""", """TUVWXYZNOPQRS"""),
    """Q""": ("""ABCDEFGHIJKLM""", """STUVWXYZNOPQR"""),
    """R""": ("""ABCDEFGHIJKLM""", """STUVWXYZNOPQR"""),
    """S""": ("""ABCDEFGHIJKLM""", """RSTUVWXYZNOPQ"""),
    """T""": ("""ABCDEFGHIJKLM""", """RSTUVWXYZNOPQ"""),
    """U""": ("""ABCDEFGHIJKLM""", """QRSTUVWXYZNOP"""),
    """V""": ("""ABCDEFGHIJKLM""", """QRSTUVWXYZNOP"""),
    """W""": ("""ABCDEFGHIJKLM""", """PQRSTUVWXYZNO"""),
    """X""": ("""ABCDEFGHIJKLM""", """PQRSTUVWXYZNO"""),
    """Y""": ("""ABCDEFGHIJKLM""", """OPQRSTUVWXYZN"""),
    """Z""": ("""ABCDEFGHIJKLM""", """OPQRSTUVWXYZN"""),
}





def        a_				(							_lowercase   ):
						return [alphabet[char] for char in key.upper()]





def        a_				(							_lowercase       ,						_lowercase   ):
						_UpperCamelCase			:					Optional[Any]     =    ''''''
						_UpperCamelCase			:					Tuple     =    0
						_UpperCamelCase			:					Optional[int]     =    generate_table(_lowercase   )
						for char in words.upper():
												cipher += get_opponent(table[count]       ,						_lowercase   )
												_UpperCamelCase			:					Optional[int]     =    (count + 1) % len(_lowercase   )
						return cipher





def        a_				(							_lowercase       ,						_lowercase   ):
						return encrypt(_lowercase       ,						_lowercase   )





def        a_				(							_lowercase       ,						_lowercase   ):
						_UpperCamelCase			:					Dict     =    0 if char in table[0] else 1
						_UpperCamelCase			:					str     =    table[row].index(_lowercase   )
						return row, col





def        a_				(							_lowercase       ,						_lowercase   ):
						_UpperCamelCase   ,							_UpperCamelCase			:					Union[str, Any]     =    get_position(_lowercase       ,						char.upper()   )
						if row == 1:
												return table[0][col]
						else:
												return table[1][col] if row == 0 else char


if __name__ == "__main__":
						import doctest

						doctest.testmod()  # Fist ensure that all our tests are passing...
						UpperCamelCase_           =input("""Enter key: """).strip()
						UpperCamelCase_           =input("""Enter text to encrypt: """).strip()
						UpperCamelCase_           =encrypt(key, text)

						print(F"Encrypted: {cipher_text}")
						print(F"Decrypted with key: {decrypt(key, cipher_text)}")



