
import os
import sys

from . import rsa_key_generator as rkg

SCREAMING_SNAKE_CASE__				=							128
SCREAMING_SNAKE_CASE__				=							256




def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: str       ,				SCREAMING_SNAKE_CASE			: int = DEFAULT_BLOCK_SIZE     )	->		list[int]:
				__lowercase								=   message.encode('ascii'     )

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




def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: list[int]       ,				SCREAMING_SNAKE_CASE			: int       ,				SCREAMING_SNAKE_CASE			: int = DEFAULT_BLOCK_SIZE     )	->		str:
				__lowercase								=   []
				for block_int in block_ints:
								__lowercase								=   []
								for i in range(block_size - 1       ,				-1       ,				-1     ):
												if len(SCREAMING_SNAKE_CASE     ) + i < message_length:
																__lowercase								=   block_int // (BYTE_SIZE**i)
																__lowercase								=   block_int % (BYTE_SIZE**i)
																block_message.insert(0       ,				chr(SCREAMING_SNAKE_CASE     )     )
								message.extend(SCREAMING_SNAKE_CASE     )
				return "".join(SCREAMING_SNAKE_CASE     )




def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: str       ,				SCREAMING_SNAKE_CASE			: tuple[int, int]       ,				SCREAMING_SNAKE_CASE			: int = DEFAULT_BLOCK_SIZE     )	->		list[int]:
				__lowercase								=   []
				__lowercase						,   __lowercase								=   key

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




def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: list[int]       ,				SCREAMING_SNAKE_CASE			: int       ,				SCREAMING_SNAKE_CASE			: tuple[int, int]       ,				SCREAMING_SNAKE_CASE			: int = DEFAULT_BLOCK_SIZE       ,				)	->		str:
				__lowercase								=   []
				__lowercase						,   __lowercase								=   key
				for block in encrypted_blocks:
								decrypted_blocks.append(pow(SCREAMING_SNAKE_CASE       ,				SCREAMING_SNAKE_CASE       ,				SCREAMING_SNAKE_CASE     )     )
				return get_text_from_blocks(SCREAMING_SNAKE_CASE       ,				SCREAMING_SNAKE_CASE       ,				SCREAMING_SNAKE_CASE     )




def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: str     )	->		tuple[int, int, int]:
				with open(SCREAMING_SNAKE_CASE     ) as fo:
								__lowercase								=   fo.read()
				__lowercase						,   __lowercase						,   __lowercase								=   content.split(','     )
				return (int(SCREAMING_SNAKE_CASE     ), int(SCREAMING_SNAKE_CASE     ), int(SCREAMING_SNAKE_CASE     ))




def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: str       ,				SCREAMING_SNAKE_CASE			: str       ,				SCREAMING_SNAKE_CASE			: str       ,				SCREAMING_SNAKE_CASE			: int = DEFAULT_BLOCK_SIZE       ,				)	->		str:
				__lowercase						,   __lowercase						,   __lowercase								=   read_key_file(SCREAMING_SNAKE_CASE     )
				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       ,				SCREAMING_SNAKE_CASE     )     )

				__lowercase								=   [str(SCREAMING_SNAKE_CASE     ) for i in encrypt_message(SCREAMING_SNAKE_CASE       ,				(n, e)       ,				SCREAMING_SNAKE_CASE     )]

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




def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: str       ,				SCREAMING_SNAKE_CASE			: str     )	->		str:
				__lowercase						,   __lowercase						,   __lowercase								=   read_key_file(SCREAMING_SNAKE_CASE     )
				with open(SCREAMING_SNAKE_CASE     ) as fo:
								__lowercase								=   fo.read()
				__lowercase						,   __lowercase						,   __lowercase								=   content.split('_'     )
				__lowercase								=   int(SCREAMING_SNAKE_CASE     )
				__lowercase								=   int(SCREAMING_SNAKE_CASE     )

				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       ,				SCREAMING_SNAKE_CASE     )     )

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

				return decrypt_message(SCREAMING_SNAKE_CASE       ,				SCREAMING_SNAKE_CASE       ,				(n, d)       ,				SCREAMING_SNAKE_CASE     )




def 				__SCREAMING_SNAKE_CASE  (						)	->		None:
				__lowercase								=   'encrypted_file.txt'
				__lowercase								=   input(R'Encrypt\Decrypt [e\d]: '     )

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

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

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

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

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

								print('\nDecryption:'     )
								print(SCREAMING_SNAKE_CASE     )


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 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: List[Any]     )	->		str:
				__lowercase								=   filter(lambda SCREAMING_SNAKE_CASE     : p.requires_grad       ,				model.parameters()     )
				__lowercase								=   sum([np.prod(p.size()     ) for p in model_parameters]     )
				return params


SCREAMING_SNAKE_CASE__				=							logging.getLogger(__name__)
class       A__  (		pl.Callback							):





							def      a__					(					self    :  List[str]	,					_UpperCAmelCase    :  Tuple	,					_UpperCAmelCase    :  List[str]							)		->						Tuple:



											"""simple docstring"""


											__lowercase								=   {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      a__					(					self    :  Dict	,					_UpperCAmelCase    :  pl.Trainer	,					_UpperCAmelCase    :  pl.LightningModule	,					_UpperCAmelCase    :  str	,					_UpperCAmelCase    :  int=True							)		->						None:



											"""simple docstring"""


											logger.info(f"""***** {type_path} results at step {trainer.global_step:05d} *****"""							)
											__lowercase								=   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
											__lowercase								=   Path(pl_module.hparams.output_dir							)
											if type_path == "test":
															__lowercase								=   od / 'test_results.txt'
															__lowercase								=   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.
															__lowercase								=   od / f"""{type_path}_results/{trainer.global_step:05d}.txt"""
															__lowercase								=   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
																			__lowercase								=   metrics[key]
																			if isinstance(_UpperCAmelCase	,					torch.Tensor							):
																							__lowercase								=   val.item()
																			__lowercase								=   f"""{key}: {val:.6f}\n"""
																			writer.write(_UpperCAmelCase							)

											if not save_generations:
															return

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





							@rank_zero_only
							def      a__					(					self    :  str	,					_UpperCAmelCase    :  Optional[int]	,					_UpperCAmelCase    :  str							)		->						Optional[int]:



											"""simple docstring"""


											try:
															__lowercase								=   pl_module.model.model.num_parameters()
											except AttributeError:
															__lowercase								=   pl_module.model.num_parameters()

											__lowercase								=   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      a__					(					self    :  Union[str, Any]	,					_UpperCAmelCase    :  pl.Trainer	,					_UpperCAmelCase    :  pl.LightningModule							)		->						Optional[Any]:



											"""simple docstring"""


											save_json(pl_module.metrics	,					pl_module.metrics_save_path							)
											return self._write_logs(_UpperCAmelCase	,					_UpperCAmelCase	,					'test'							)





							@rank_zero_only
							def      a__					(					self    :  int	,					_UpperCAmelCase    :  pl.Trainer	,					_UpperCAmelCase    :  Tuple							)		->						str:



											"""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 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: List[Any]       ,				SCREAMING_SNAKE_CASE			: List[str]       ,				SCREAMING_SNAKE_CASE			: Union[str, Any]=1       ,				SCREAMING_SNAKE_CASE			: str=False     )	->		List[str]:
				if metric == "rouge2":
								__lowercase								=   '{val_avg_rouge2:.4f}-{step_count}'
				elif metric == "bleu":
								__lowercase								=   '{val_avg_bleu:.4f}-{step_count}'
				elif metric == "loss":
								__lowercase								=   '{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.'     )

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




def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: Any       ,				SCREAMING_SNAKE_CASE			: int     )	->		Union[str, Any]:
				return EarlyStopping(
				    monitor=F"""val_{metric}"""       ,				mode='min' if 'loss' in metric else 'max'       ,				patience=SCREAMING_SNAKE_CASE       ,				verbose=SCREAMING_SNAKE_CASE       ,				)





