




import csv
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Optional

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter

from transformers import HfArgumentParser



def    UpperCAmelCase							(  _snake_case=None    ,			_snake_case=None				):
							return field(default_factory=lambda: default    ,			metadata=_snake_case				)


@dataclass
class 				__UpperCamelCase      :





				'''simple docstring'''



				__a				:			str					    =field(
				    metadata={"""help""": """The csv file to plot."""}  ,       )
				__a				:			bool					    =field(
				    default=__UpperCAmelCase  ,       metadata={"""help""": """Whether to plot along batch size or sequence length. Defaults to sequence length."""}  ,       )
				__a				:			bool					    =field(
				    default=__UpperCAmelCase  ,       metadata={"""help""": """Whether the csv file has time results or memory results. Defaults to memory results."""}  ,       )
				__a				:			bool					    =field(
				    default=__UpperCAmelCase  ,       metadata={"""help""": """Disable logarithmic scale when plotting"""}  ,       )
				__a				:			bool					    =field(
				    default=__UpperCAmelCase  ,       metadata={
				        """help""": """Whether the csv file has training results or inference results. Defaults to inference results."""
				    }  ,       )
				__a				:			Optional[str]					    =field(
				    default=__UpperCAmelCase  ,       metadata={"""help""": """Filename under which the plot will be saved. If unused no plot is saved."""}  ,       )
				__a				:			Optional[List[str]]					    =list_field(
				    default=__UpperCAmelCase  ,       metadata={"""help""": """List of model names that are used instead of the ones in the csv file."""}	)




def    UpperCAmelCase							(  _snake_case				):
							try:
														int(_snake_case				)
														return True
							except ValueError:
														return False



def    UpperCAmelCase							(  _snake_case				):
							try:
														float(_snake_case				)
														return True
							except ValueError:
														return False


class 				__UpperCamelCase      :





				'''simple docstring'''



				def __init__(			self							,			UpperCAmelCase_    ):
											lowerCAmelCase =		args
											lowerCAmelCase =		defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}}    )

											with open(self.args.csv_file							,			newline=''''''    ) as csv_file:
																		lowerCAmelCase =		csv.DictReader(UpperCAmelCase_    )
																		for row in reader:
																									lowerCAmelCase =		row['''model''']
																									self.result_dict[model_name]["bsz"].append(int(row['''batch_size''']    )    )
																									self.result_dict[model_name]["seq_len"].append(int(row['''sequence_length''']    )    )
																									if can_convert_to_int(row['''result''']    ):
																																# value is not None
																																lowerCAmelCase =		int(row['''result''']    )
																									elif can_convert_to_float(row['''result''']    ):
																																# value is not None
																																lowerCAmelCase =		float(row['''result''']    )






				def    __snake_case		(			self    ):
											lowerCAmelCase ,  lowerCAmelCase =		plt.subplots()
											lowerCAmelCase =		'''Time usage''' if self.args.is_time else '''Memory usage'''
											lowerCAmelCase =		title_str + ''' for training''' if self.args.is_train else title_str + ''' for inference'''

											if not self.args.no_log_scale:
																		# set logarithm scales
																		ax.set_xscale('''log'''    )
																		ax.set_yscale('''log'''    )

											for axis in [ax.xaxis, ax.yaxis]:
																		axis.set_major_formatter(ScalarFormatter()    )

											for model_name_idx, model_name in enumerate(self.result_dict.keys()    ):
																		lowerCAmelCase =		sorted(set(self.result_dict[model_name]['''bsz''']    )    )
																		lowerCAmelCase =		sorted(set(self.result_dict[model_name]['''seq_len''']    )    )
																		lowerCAmelCase =		self.result_dict[model_name]['''result''']

																		((lowerCAmelCase) ,  (lowerCAmelCase)) =		(
																		    (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes)
																		)

																		lowerCAmelCase =		(
																		    model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx]
																		)

																		for inner_loop_value in inner_loop_array:
																									if self.args.plot_along_batch:
																																lowerCAmelCase =		np.asarray(
																																    [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results]							,			dtype=UpperCAmelCase_							,			)
																									else:
																																lowerCAmelCase =		np.asarray(
																																    [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results]							,			dtype=np.floataa							,			)

																									((lowerCAmelCase) ,  (lowerCAmelCase)) =		(
																									    ('''batch_size''', '''len''') if self.args.plot_along_batch else ('''in #tokens''', '''bsz''')
																									)

																									lowerCAmelCase =		np.asarray(UpperCAmelCase_							,			UpperCAmelCase_    )[: len(UpperCAmelCase_    )]
																									plt.scatter(
																									    UpperCAmelCase_							,			UpperCAmelCase_							,			label=F"""{label_model_name} - {inner_loop_label}: {inner_loop_value}"""    )
																									plt.plot(UpperCAmelCase_							,			UpperCAmelCase_							,			'''--'''    )

																		title_str += F""" {label_model_name} vs."""

											lowerCAmelCase =		title_str[:-4]
											lowerCAmelCase =		'''Time in s''' if self.args.is_time else '''Memory in MB'''

											# plot
											plt.title(UpperCAmelCase_    )
											plt.xlabel(UpperCAmelCase_    )
											plt.ylabel(UpperCAmelCase_    )
											plt.legend()

											if self.args.figure_png_file is not None:
																		plt.savefig(self.args.figure_png_file    )
											else:
																		plt.show()




def    UpperCAmelCase							(  ):
							lowerCAmelCase =		HfArgumentParser(_snake_case				)
							lowerCAmelCase =		parser.parse_args_into_dataclasses()[0]
							lowerCAmelCase =		Plot(args=_snake_case				)
							plot.plot()


if __name__ == "__main__":
		main()









import os
import sys

from . import rsa_key_generator as rkg

UpperCAmelCase_    =128
UpperCAmelCase_    =256



def    UpperCAmelCase							(  _snake_case    ,			_snake_case = DEFAULT_BLOCK_SIZE				):
							lowerCAmelCase =		message.encode('''ascii'''				)

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



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



def    UpperCAmelCase							(  _snake_case    ,			_snake_case    ,			_snake_case = DEFAULT_BLOCK_SIZE				):
							lowerCAmelCase =		[]
							lowerCAmelCase ,  lowerCAmelCase =		key

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



def    UpperCAmelCase							(  _snake_case    ,			_snake_case    ,			_snake_case    ,			_snake_case = DEFAULT_BLOCK_SIZE    ,			):
							lowerCAmelCase =		[]
							lowerCAmelCase ,  lowerCAmelCase =		key
							for block in encrypted_blocks:
														decrypted_blocks.append(pow(_snake_case    ,			_snake_case    ,			_snake_case				)				)
							return get_text_from_blocks(_snake_case    ,			_snake_case    ,			_snake_case				)



def    UpperCAmelCase							(  _snake_case				):
							with open(_snake_case				) as fo:
														lowerCAmelCase =		fo.read()
							lowerCAmelCase ,  lowerCAmelCase ,  lowerCAmelCase =		content.split(''','''				)
							return (int(_snake_case				), int(_snake_case				), int(_snake_case				))



def    UpperCAmelCase							(  _snake_case    ,			_snake_case    ,			_snake_case    ,			_snake_case = DEFAULT_BLOCK_SIZE    ,			):
							lowerCAmelCase ,  lowerCAmelCase ,  lowerCAmelCase =		read_key_file(_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    ,			_snake_case				)				)

							lowerCAmelCase =		[str(_snake_case				) for i in encrypt_message(_snake_case    ,			(n, e)    ,			_snake_case				)]

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



def    UpperCAmelCase							(  _snake_case    ,			_snake_case				):
							lowerCAmelCase ,  lowerCAmelCase ,  lowerCAmelCase =		read_key_file(_snake_case				)
							with open(_snake_case				) as fo:
														lowerCAmelCase =		fo.read()
							lowerCAmelCase ,  lowerCAmelCase ,  lowerCAmelCase =		content.split('''_'''				)
							lowerCAmelCase =		int(_snake_case				)
							lowerCAmelCase =		int(_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    ,			_snake_case				)				)

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

							return decrypt_message(_snake_case    ,			_snake_case    ,			(n, d)    ,			_snake_case				)



def    UpperCAmelCase							(  ):
							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(_snake_case    ,			_snake_case    ,			_snake_case				)

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

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

														print('''\nDecryption:'''				)
														print(_snake_case				)


if __name__ == "__main__":
		main()



