






import os
import sys

from . import rsa_key_generator as rkg

__snake_case			:			List[str]			   =   1_28
__snake_case			:			List[Any]			   =   2_56







def 		_UpperCamelCase      (			UpperCamelCase_				:    str			,				UpperCamelCase_				:    int = DEFAULT_BLOCK_SIZE						)     ->      list[int]:

						"""simple docstring"""



						lowerCAmelCase__			  =  message.encode('ascii'						)

						lowerCAmelCase__			  =  []
						for block_start in range(0			,				len(UpperCamelCase_						)			,				UpperCamelCase_						):
												lowerCAmelCase__			  =  0
												for i in range(UpperCamelCase_			,				min(block_start + block_size			,				len(UpperCamelCase_						)						)						):
																		block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size))
												block_ints.append(UpperCamelCase_						)
						return block_ints







def 		_UpperCamelCase      (			UpperCamelCase_				:    list[int]			,				UpperCamelCase_				:    int			,				UpperCamelCase_				:    int = DEFAULT_BLOCK_SIZE						)     ->      str:

						"""simple docstring"""



						lowerCAmelCase__			  =  []
						for block_int in block_ints:
												lowerCAmelCase__			  =  []
												for i in range(block_size - 1			,				-1			,				-1						):
																		if len(UpperCamelCase_						) + i < message_length:
																								lowerCAmelCase__			  =  block_int // (BYTE_SIZE**i)
																								lowerCAmelCase__			  =  block_int % (BYTE_SIZE**i)
																								block_message.insert(0			,				chr(UpperCamelCase_						)						)
												message.extend(UpperCamelCase_						)
						return "".join(UpperCamelCase_						)







def 		_UpperCamelCase      (			UpperCamelCase_				:    str			,				UpperCamelCase_				:    tuple[int, int]			,				UpperCamelCase_				:    int = DEFAULT_BLOCK_SIZE						)     ->      list[int]:

						"""simple docstring"""



						lowerCAmelCase__			  =  []
						lowerCAmelCase__  ,				lowerCAmelCase__			  =  key

						for block in get_blocks_from_text(UpperCamelCase_			,				UpperCamelCase_						):
												encrypted_blocks.append(pow(UpperCamelCase_			,				UpperCamelCase_			,				UpperCamelCase_						)						)
						return encrypted_blocks







def 		_UpperCamelCase      (			UpperCamelCase_				:    list[int]			,				UpperCamelCase_				:    int			,				UpperCamelCase_				:    tuple[int, int]			,				UpperCamelCase_				:    int = DEFAULT_BLOCK_SIZE			,				)     ->      str:

						"""simple docstring"""



						lowerCAmelCase__			  =  []
						lowerCAmelCase__  ,				lowerCAmelCase__			  =  key
						for block in encrypted_blocks:
												decrypted_blocks.append(pow(UpperCamelCase_			,				UpperCamelCase_			,				UpperCamelCase_						)						)
						return get_text_from_blocks(UpperCamelCase_			,				UpperCamelCase_			,				UpperCamelCase_						)







def 		_UpperCamelCase      (			UpperCamelCase_				:    str						)     ->      tuple[int, int, int]:

						"""simple docstring"""



						with open(UpperCamelCase_						) as fo:
												lowerCAmelCase__			  =  fo.read()
						lowerCAmelCase__  ,				lowerCAmelCase__  ,				lowerCAmelCase__			  =  content.split(','						)
						return (int(UpperCamelCase_						), int(UpperCamelCase_						), int(UpperCamelCase_						))







def 		_UpperCamelCase      (			UpperCamelCase_				:    str			,				UpperCamelCase_				:    str			,				UpperCamelCase_				:    str			,				UpperCamelCase_				:    int = DEFAULT_BLOCK_SIZE			,				)     ->      str:

						"""simple docstring"""



						lowerCAmelCase__  ,				lowerCAmelCase__  ,				lowerCAmelCase__			  =  read_key_file(UpperCamelCase_						)
						if key_size < block_size * 8:
												sys.exit(
												    'ERROR: Block size is {} bits and key size is {} bits. The RSA cipher '
												    'requires the block size to be equal to or greater than the key size. '
												    'Either decrease the block size or use different keys.'.format(
												        block_size * 8			,				UpperCamelCase_						)						)

						lowerCAmelCase__			  =  [str(UpperCamelCase_						) for i in encrypt_message(UpperCamelCase_			,				(n, e)			,				UpperCamelCase_						)]

						lowerCAmelCase__			  =  ','.join(UpperCamelCase_						)
						lowerCAmelCase__			  =  F"{len(UpperCamelCase_						)}_{block_size}_{encrypted_content}"
						with open(UpperCamelCase_			,				'w'						) as fo:
												fo.write(UpperCamelCase_						)
						return encrypted_content







def 		_UpperCamelCase      (			UpperCamelCase_				:    str			,				UpperCamelCase_				:    str						)     ->      str:

						"""simple docstring"""



						lowerCAmelCase__  ,				lowerCAmelCase__  ,				lowerCAmelCase__			  =  read_key_file(UpperCamelCase_						)
						with open(UpperCamelCase_						) as fo:
												lowerCAmelCase__			  =  fo.read()
						lowerCAmelCase__  ,				lowerCAmelCase__  ,				lowerCAmelCase__			  =  content.split('_'						)
						lowerCAmelCase__			  =  int(UpperCamelCase_						)
						lowerCAmelCase__			  =  int(UpperCamelCase_						)

						if key_size < block_size * 8:
												sys.exit(
												    'ERROR: Block size is {} bits and key size is {} bits. The RSA cipher '
												    'requires the block size to be equal to or greater than the key size. '
												    'Did you specify the correct key file and encrypted file?'.format(
												        block_size * 8			,				UpperCamelCase_						)						)

						lowerCAmelCase__			  =  []
						for block in encrypted_message.split(','						):
												encrypted_blocks.append(int(UpperCamelCase_						)						)

						return decrypt_message(UpperCamelCase_			,				UpperCamelCase_			,				(n, d)			,				UpperCamelCase_						)







def 		_UpperCamelCase      (			)     ->      None:

						"""simple docstring"""



						lowerCAmelCase__			  =  'encrypted_file.txt'
						lowerCAmelCase__			  =  input(r'Encrypt\Decrypt [e\d]: '						)

						if response.lower().startswith('e'						):
												lowerCAmelCase__			  =  'encrypt'
						elif response.lower().startswith('d'						):
												lowerCAmelCase__			  =  'decrypt'

						if mode == "encrypt":
												if not os.path.exists('rsa_pubkey.txt'						):
																		rkg.make_key_files('rsa'			,				1024						)

												lowerCAmelCase__			  =  input('\nEnter message: '						)
												lowerCAmelCase__			  =  'rsa_pubkey.txt'
												print(F"Encrypting and writing to {filename}..."						)
												lowerCAmelCase__			  =  encrypt_and_write_to_file(UpperCamelCase_			,				UpperCamelCase_			,				UpperCamelCase_						)

												print('\nEncrypted text:'						)
												print(UpperCamelCase_						)

						elif mode == "decrypt":
												lowerCAmelCase__			  =  'rsa_privkey.txt'
												print(F"Reading from {filename} and decrypting..."						)
												lowerCAmelCase__			  =  read_from_file_and_decrypt(UpperCamelCase_			,				UpperCamelCase_						)
												print('writing decryption to rsa_decryption.txt...'						)
												with open('rsa_decryption.txt'			,				'w'						) as dec:
																		dec.write(UpperCamelCase_						)

												print('\nDecryption:'						)
												print(UpperCamelCase_						)


if __name__ == "__main__":
					main()













import logging
from pathlib import Path

import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only

from utils import save_json







def 		_UpperCamelCase      (			UpperCamelCase_				:    Tuple						)     ->      str:

						"""simple docstring"""



						lowerCAmelCase__			  =  filter(lambda UpperCamelCase_						: p.requires_grad			,				model.parameters()						)
						lowerCAmelCase__			  =  sum([np.prod(p.size()						) for p in model_parameters]						)
						return params


__snake_case			:			Dict			   =   logging.getLogger(__name__)


class 			__SCREAMING_SNAKE_CASE    (      pl.Callback):






						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase   ,  _UpperCamelCase      ):






												"""simple docstring"""
												lowerCAmelCase__			  =  {F"lr_group_{i}": param['lr'] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups      )}
												pl_module.logger.log_metrics(_UpperCamelCase      )






						@rank_zero_only
						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase   ,  _UpperCamelCase   ,  _UpperCamelCase   ,  _UpperCamelCase=True      ):






												"""simple docstring"""
												logger.info(F"***** {type_path} results at step {trainer.global_step:05d} *****"      )
												lowerCAmelCase__			  =  trainer.callback_metrics
												trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['log', 'progress_bar', 'preds']}      )
												# Log results
												lowerCAmelCase__			  =  Path(pl_module.hparams.output_dir      )
												if type_path == "test":
																		lowerCAmelCase__			  =  od / 'test_results.txt'
																		lowerCAmelCase__			  =  od / 'test_generations.txt'
												else:
																		# this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json
																		# If people want this it will be easy enough to add back.
																		lowerCAmelCase__			  =  od / F"{type_path}_results/{trainer.global_step:05d}.txt"
																		lowerCAmelCase__			  =  od / F"{type_path}_generations/{trainer.global_step:05d}.txt"
																		results_file.parent.mkdir(exist_ok=_UpperCamelCase      )
																		generations_file.parent.mkdir(exist_ok=_UpperCamelCase      )
												with open(_UpperCamelCase   ,  'a+'      ) as writer:
																		for key in sorted(_UpperCamelCase      ):
																								if key in ["log", "progress_bar", "preds"]:
																														continue
																								lowerCAmelCase__			  =  metrics[key]
																								if isinstance(_UpperCamelCase   ,  torch.Tensor      ):
																														lowerCAmelCase__			  =  val.item()
																								lowerCAmelCase__			  =  F"{key}: {val:.6f}\n"
																								writer.write(_UpperCamelCase      )

												if not save_generations:
																		return

												if "preds" in metrics:
																		lowerCAmelCase__			  =  '\n'.join(metrics['preds']      )
																		generations_file.open('w+'      ).write(_UpperCamelCase      )






						@rank_zero_only
						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase   ,  _UpperCamelCase      ):






												"""simple docstring"""
												try:
																		lowerCAmelCase__			  =  pl_module.model.model.num_parameters()
												except AttributeError:
																		lowerCAmelCase__			  =  pl_module.model.num_parameters()

												lowerCAmelCase__			  =  count_trainable_parameters(_UpperCamelCase      )
												# mp stands for million parameters
												trainer.logger.log_metrics({'n_params': npars, 'mp': npars / 1E6, 'grad_mp': n_trainable_pars / 1E6}      )






						@rank_zero_only
						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase   ,  _UpperCamelCase      ):






												"""simple docstring"""
												save_json(pl_module.metrics   ,  pl_module.metrics_save_path      )
												return self._write_logs(_UpperCamelCase   ,  _UpperCamelCase   ,  'test'      )







						@rank_zero_only
						def 					UpperCamelCase__					(		self   ,  _UpperCamelCase   ,  _UpperCamelCase      ):






												"""simple docstring"""
												save_json(pl_module.metrics   ,  pl_module.metrics_save_path      )
												# Uncommenting this will save val generations
												# return self._write_logs(trainer, pl_module, "valid")







def 		_UpperCamelCase      (			UpperCamelCase_				:    Union[str, Any]			,				UpperCamelCase_				:    Union[str, Any]			,				UpperCamelCase_				:    List[Any]=1			,				UpperCamelCase_				:    List[str]=False						)     ->      Optional[Any]:

						"""simple docstring"""



						if metric == "rouge2":
												lowerCAmelCase__			  =  '{val_avg_rouge2:.4f}-{step_count}'
						elif metric == "bleu":
												lowerCAmelCase__			  =  '{val_avg_bleu:.4f}-{step_count}'
						elif metric == "loss":
												lowerCAmelCase__			  =  '{val_avg_loss:.4f}-{step_count}'
						else:
												raise NotImplementedError(
												    F"seq2seq callbacks only support rouge2, bleu and loss, got {metric}, You can make your own by adding to"
												    ' this function.'						)

						lowerCAmelCase__			  =  ModelCheckpoint(
						    dirpath=UpperCamelCase_			,				filename=UpperCamelCase_			,				monitor=F"val_{metric}"			,				mode='min' if 'loss' in metric else 'max'			,				save_top_k=UpperCamelCase_			,				)
						return checkpoint_callback







def 		_UpperCamelCase      (			UpperCamelCase_				:    Union[str, Any]			,				UpperCamelCase_				:    int						)     ->      Dict:

						"""simple docstring"""



						return EarlyStopping(
						    monitor=F"val_{metric}"			,				mode='min' if 'loss' in metric else 'max'			,				patience=UpperCamelCase_			,				verbose=UpperCamelCase_			,				)





