
import os
import sys

from . import rsa_key_generator as rkg

lowercase__						:str					    =       128
lowercase__						:str					    =       256



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__ = DEFAULT_BLOCK_SIZE						):
					'''simple docstring'''
					lowercase		      =		message.encode('''ascii'''						)

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



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



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__ = DEFAULT_BLOCK_SIZE						):
					'''simple docstring'''
					lowercase		      =		[]
					lowercase      ,		lowercase		      =		key

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



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__ = DEFAULT_BLOCK_SIZE					,     ):
					'''simple docstring'''
					lowercase		      =		[]
					lowercase      ,		lowercase		      =		key
					for block in encrypted_blocks:
										decrypted_blocks.append(pow(lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__						)						)
					return get_text_from_blocks(lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__						)



def 			UpperCamelCase       (				lowerCAmelCase__						):
					'''simple docstring'''
					with open(lowerCAmelCase__						) as fo:
										lowercase		      =		fo.read()
					lowercase      ,		lowercase      ,		lowercase		      =		content.split(''','''						)
					return (int(lowerCAmelCase__						), int(lowerCAmelCase__						), int(lowerCAmelCase__						))



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__ = DEFAULT_BLOCK_SIZE					,     ):
					'''simple docstring'''
					lowercase      ,		lowercase      ,		lowercase		      =		read_key_file(lowerCAmelCase__						)
					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					,     lowerCAmelCase__						)						)

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

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



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__						):
					'''simple docstring'''
					lowercase      ,		lowercase      ,		lowercase		      =		read_key_file(lowerCAmelCase__						)
					with open(lowerCAmelCase__						) as fo:
										lowercase		      =		fo.read()
					lowercase      ,		lowercase      ,		lowercase		      =		content.split('''_'''						)
					lowercase		      =		int(lowerCAmelCase__						)
					lowercase		      =		int(lowerCAmelCase__						)

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

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

					return decrypt_message(lowerCAmelCase__					,     lowerCAmelCase__					,     (n, d)					,     lowerCAmelCase__						)



def 			UpperCamelCase       (				):
					'''simple docstring'''
					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(lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__						)

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

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

										print('''\nDecryption:'''						)
										print(lowerCAmelCase__						)


if __name__ == "__main__":
							main()






import os
import random
from pathlib import Path
from typing import List

import numpy as np
import torch
from torch.cuda.amp import GradScaler

from .utils import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    get_pretty_name,
    is_tpu_available,
    is_xpu_available,
    save,
)


if is_tpu_available(check_device=False):
							import torch_xla.core.xla_model as xm

from .logging import get_logger
from .state import PartialState


lowercase__						:Optional[Any]					    =       get_logger(__name__)



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__ = None					,     ):
					'''simple docstring'''
					# Model states
					for i, state in enumerate(lowerCAmelCase__						):
										lowercase		      =		f'{MODEL_NAME}.bin' if i == 0 else f'{MODEL_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										save(lowerCAmelCase__					,     lowerCAmelCase__						)
										logger.info(f'Model weights saved in {output_model_file}'						)
					# Optimizer states
					for i, opt in enumerate(lowerCAmelCase__						):
										lowercase		      =		opt.state_dict()
										lowercase		      =		f'{OPTIMIZER_NAME}.bin' if i == 0 else f'{OPTIMIZER_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										save(lowerCAmelCase__					,     lowerCAmelCase__						)
										logger.info(f'Optimizer state saved in {output_optimizer_file}'						)
					# Scheduler states
					for i, scheduler in enumerate(lowerCAmelCase__						):
										lowercase		      =		scheduler.state_dict()
										lowercase		      =		f'{SCHEDULER_NAME}.bin' if i == 0 else f'{SCHEDULER_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										save(lowerCAmelCase__					,     lowerCAmelCase__						)
										logger.info(f'Scheduler state saved in {output_scheduler_file}'						)
					# GradScaler state
					if scaler is not None:
										lowercase		      =		scaler.state_dict()
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										torch.save(lowerCAmelCase__					,     lowerCAmelCase__						)
										logger.info(f'Gradient scaler state saved in {output_scaler_file}'						)
					# Random number generator states
					lowercase		      =		{}
					lowercase		      =		f'{RNG_STATE_NAME}_{process_index}.pkl'
					lowercase		      =		random.getstate()
					lowercase		      =		np.random.get_state()
					lowercase		      =		torch.get_rng_state()
					if is_xpu_available():
										lowercase		      =		torch.xpu.get_rng_state_all()
					else:
										lowercase		      =		torch.cuda.get_rng_state_all()
					if is_tpu_available():
										lowercase		      =		xm.get_rng_state()
					lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
					torch.save(lowerCAmelCase__					,     lowerCAmelCase__						)
					logger.info(f'Random states saved in {output_states_file}'						)
					return output_dir



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__=None					,     lowerCAmelCase__=None					,     **lowerCAmelCase__					,     ):
					'''simple docstring'''
					if map_location not in [None, "cpu", "on_device"]:
										raise TypeError(
										    '''Unsupported optimizer map location passed, please choose one of `None`, `\'cpu\'`, or `\'on_device\'`'''						)
					if map_location is None:
										lowercase		      =		'''cpu'''
					elif map_location == "on_device":
										lowercase		      =		PartialState().device
					# Model states
					for i, model in enumerate(lowerCAmelCase__						):
										lowercase		      =		f'{MODEL_NAME}.bin' if i == 0 else f'{MODEL_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										models[i].load_state_dict(torch.load(lowerCAmelCase__					,     map_location=lowerCAmelCase__						)					,     **lowerCAmelCase__						)
					logger.info('''All model weights loaded successfully'''						)

					# Optimizer states
					for i, opt in enumerate(lowerCAmelCase__						):
										lowercase		      =		f'{OPTIMIZER_NAME}.bin' if i == 0 else f'{OPTIMIZER_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										lowercase		      =		torch.load(lowerCAmelCase__					,     map_location=lowerCAmelCase__						)
										optimizers[i].load_state_dict(lowerCAmelCase__						)
					logger.info('''All optimizer states loaded successfully'''						)

					# Scheduler states
					for i, scheduler in enumerate(lowerCAmelCase__						):
										lowercase		      =		f'{SCHEDULER_NAME}.bin' if i == 0 else f'{SCHEDULER_NAME}_{i}.bin'
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										scheduler.load_state_dict(torch.load(lowerCAmelCase__						)						)
					logger.info('''All scheduler states loaded successfully'''						)

					# GradScaler state
					if scaler is not None:
										lowercase		      =		os.path.join(lowerCAmelCase__					,     lowerCAmelCase__						)
										scaler.load_state_dict(torch.load(lowerCAmelCase__						)						)
										logger.info('''GradScaler state loaded successfully'''						)

					# Random states
					try:
										lowercase		      =		torch.load(os.path.join(lowerCAmelCase__					,     f'{RNG_STATE_NAME}_{process_index}.pkl'						)						)
										random.setstate(states['''random_state''']						)
										np.random.set_state(states['''numpy_random_seed''']						)
										torch.set_rng_state(states['''torch_manual_seed''']						)
										if is_xpu_available():
															torch.xpu.set_rng_state_all(states['''torch_xpu_manual_seed''']						)
										else:
															torch.cuda.set_rng_state_all(states['''torch_cuda_manual_seed''']						)
										if is_tpu_available():
															xm.set_rng_state(states['''xm_seed''']						)
										logger.info('''All random states loaded successfully'''						)
					except Exception:
										logger.info('''Could not load random states'''						)



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__ = 0						):
					'''simple docstring'''
					lowercase		      =		Path(lowerCAmelCase__						) / f'custom_checkpoint_{index}.pkl'
					logger.info(f'Saving the state of {get_pretty_name(lowerCAmelCase__						)} to {save_location}'						)
					torch.save(obj.state_dict()					,     lowerCAmelCase__						)



def 			UpperCamelCase       (				lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__ = 0						):
					'''simple docstring'''
					lowercase		      =		f'{path}/custom_checkpoint_{index}.pkl'
					logger.info(f'Loading the state of {get_pretty_name(lowerCAmelCase__						)} from {load_location}'						)
					obj.load_state_dict(torch.load(lowerCAmelCase__					,     map_location='''cpu'''						)						)




