



"""simple docstring"""







import os
import sys

from . import rsa_key_generator as rkg

UpperCAmelCase:  int			     =				128
UpperCAmelCase:  Dict			     =				256


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase = DEFAULT_BLOCK_SIZE      ):
		_lowercase				: Any     =   message.encode("""ascii"""      )

		_lowercase				: Dict     =   []
		for block_start in range(0   ,				len(__UpperCAmelCase      )   ,				__UpperCAmelCase      ):
				_lowercase				: int     =   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  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase = DEFAULT_BLOCK_SIZE      ):
		_lowercase				: list[str]     =   []
		for block_int in block_ints:
				_lowercase				: list[str]     =   []
				for i in range(block_size - 1   ,				-1   ,				-1      ):
						if len(__UpperCAmelCase      ) + i < message_length:
								_lowercase				: Optional[int]     =   block_int // (BYTE_SIZE**i)
								_lowercase				: List[Any]     =   block_int % (BYTE_SIZE**i)
								block_message.insert(0   ,				chr(__UpperCAmelCase      )      )
				message.extend(__UpperCAmelCase      )
		return "".join(__UpperCAmelCase      )


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase = DEFAULT_BLOCK_SIZE      ):
		_lowercase				: int     =   []
		_lowercase     ,  _lowercase				: List[Any]     =   key

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


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase = DEFAULT_BLOCK_SIZE   ,				):
		_lowercase				: Tuple     =   []
		_lowercase     ,  _lowercase				: Optional[int]     =   key
		for block in encrypted_blocks:
				decrypted_blocks.append(pow(__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      )      )
		return get_text_from_blocks(__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      )


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase      ):
		with open(__UpperCAmelCase      ) as fo:
				_lowercase				: Optional[Any]     =   fo.read()
		_lowercase     ,  _lowercase     ,  _lowercase				: Optional[Any]     =   content.split(""","""      )
		return (int(__UpperCAmelCase      ), int(__UpperCAmelCase      ), int(__UpperCAmelCase      ))


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase = DEFAULT_BLOCK_SIZE   ,				):
		_lowercase     ,  _lowercase     ,  _lowercase				: Optional[Any]     =   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      )      )

		_lowercase				: str     =   [str(__UpperCAmelCase      ) for i in encrypt_message(__UpperCAmelCase   ,				(n, e)   ,				__UpperCAmelCase      )]

		_lowercase				: List[str]     =   """,""".join(__UpperCAmelCase      )
		_lowercase				: List[Any]     =   F"""{len(__UpperCAmelCase      )}_{block_size}_{encrypted_content}"""
		with open(__UpperCAmelCase   ,				"""w"""      ) as fo:
				fo.write(__UpperCAmelCase      )
		return encrypted_content


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase      ):
		_lowercase     ,  _lowercase     ,  _lowercase				: List[Any]     =   read_key_file(__UpperCAmelCase      )
		with open(__UpperCAmelCase      ) as fo:
				_lowercase				: List[Any]     =   fo.read()
		_lowercase     ,  _lowercase     ,  _lowercase				: int     =   content.split("""_"""      )
		_lowercase				: Union[str, Any]     =   int(__UpperCAmelCase      )
		_lowercase				: Union[str, Any]     =   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      )      )

		_lowercase				: Any     =   []
		for block in encrypted_message.split(""","""      ):
				encrypted_blocks.append(int(__UpperCAmelCase      )      )

		return decrypt_message(__UpperCAmelCase   ,				__UpperCAmelCase   ,				(n, d)   ,				__UpperCAmelCase      )


def  __SCREAMING_SNAKE_CASE (  ):
		_lowercase				: Optional[int]     =   """encrypted_file.txt"""
		_lowercase				: Tuple     =   input(R"""Encrypt\Decrypt [e\d]: """      )

		if response.lower().startswith("""e"""      ):
				_lowercase				: Union[str, Any]     =   """encrypt"""
		elif response.lower().startswith("""d"""      ):
				_lowercase				: Any     =   """decrypt"""

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

				_lowercase				: Optional[int]     =   input("""\nEnter message: """      )
				_lowercase				: Any     =   """rsa_pubkey.txt"""
				print(F"""Encrypting and writing to {filename}..."""      )
				_lowercase				: Optional[int]     =   encrypt_and_write_to_file(__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      )

				print("""\nEncrypted text:"""      )
				print(__UpperCAmelCase      )

		elif mode == "decrypt":
				_lowercase				: Any     =   """rsa_privkey.txt"""
				print(F"""Reading from {filename} and decrypting..."""      )
				_lowercase				: List[str]     =   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()










"""simple docstring"""





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    a__       (       _SCREAMING_SNAKE_CASE=None	,						_SCREAMING_SNAKE_CASE=None     ):




		"""simple docstring"""


		return field(default_factory=lambda: default	,						metadata=_SCREAMING_SNAKE_CASE     )





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



def    a__       (       _SCREAMING_SNAKE_CASE     ):




		"""simple docstring"""


		try:
				int(_SCREAMING_SNAKE_CASE     )
				return True
		except ValueError:
				return False


def    a__       (       _SCREAMING_SNAKE_CASE     ):




		"""simple docstring"""


		try:
				float(_SCREAMING_SNAKE_CASE     )
				return True
		except ValueError:
				return False





class 							_lowerCamelCase   :


						def __init__(self ,				__a		)			-> Tuple:
								UpperCamelCase =						args
								UpperCamelCase =						defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}}		)

								with open(self.args.csv_file ,				newline=""		) as csv_file:
										UpperCamelCase =						csv.DictReader(__a		)
										for row in reader:
												UpperCamelCase =						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
														UpperCamelCase =						int(row["result"]		)
												elif can_convert_to_float(row["result"]		):
														# value is not None
														UpperCamelCase =						float(row["result"]		)




						def      snake_case_ (self		)			-> Optional[int]:
								UpperCamelCase ,					UpperCamelCase =						plt.subplots()
								UpperCamelCase =						"Time usage" if self.args.is_time else "Memory usage"
								UpperCamelCase =						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()		):
										UpperCamelCase =						sorted(set(self.result_dict[model_name]["bsz"]		)		)
										UpperCamelCase =						sorted(set(self.result_dict[model_name]["seq_len"]		)		)
										UpperCamelCase =						self.result_dict[model_name]["result"]

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

										UpperCamelCase =						(
										    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:
														UpperCamelCase =						np.asarray(
														    [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] ,				dtype=__a ,				)
												else:
														UpperCamelCase =						np.asarray(
														    [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] ,				dtype=np.floataa ,				)

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

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

										title_str += F" {label_model_name} vs."

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

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

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



def    a__       (       ):




		"""simple docstring"""


		UpperCamelCase =						HfArgumentParser(_SCREAMING_SNAKE_CASE     )
		UpperCamelCase =						parser.parse_args_into_dataclasses()[0]
		UpperCamelCase =						Plot(args=_SCREAMING_SNAKE_CASE     )
		plot.plot()


if __name__ == "__main__":
						main()






