
"""simple docstring"""


import itertools
from dataclasses import dataclass
from io import StringIO
from typing import Optional

import pyarrow as pa

import datasets
from datasets.features.features import require_storage_cast
from datasets.table import table_cast


__A 		= datasets.utils.logging.get_logger(__name__)







@dataclass
class 	lowerCamelCase__      (      datasets.BuilderConfig       ):





			'''simple docstring'''
			lowerCamelCase						      =	None
			lowerCamelCase						      =	"utf-8"
			lowerCamelCase						      =	None
			lowerCamelCase						      =	10 << 20  # 10MB
			lowerCamelCase						      =	False
			lowerCamelCase						      =	"line"







class 	lowerCamelCase__      (      datasets.ArrowBasedBuilder       ):





			'''simple docstring'''
			lowerCamelCase						      =	TextConfig



			def       _lowerCAmelCase	(							self						)				->  List[Any]:
				return datasets.DatasetInfo(features=self.config.features						)



			def       _lowerCAmelCase	(							self  ,  __UpperCAmelCase						)				->  Any:
				if not self.config.data_files:
					raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}'''						)
				_lowerCAmelCase			=dl_manager.download_and_extract(self.config.data_files						)
				if isinstance(__UpperCAmelCase  ,  (str, list, tuple)						):
					_lowerCAmelCase			=data_files
					if isinstance(__UpperCAmelCase  ,  __UpperCAmelCase						):
						_lowerCAmelCase			=[files]
					_lowerCAmelCase			=[dl_manager.iter_files(__UpperCAmelCase						) for file in files]
					return [datasets.SplitGenerator(name=datasets.Split.TRAIN  ,  gen_kwargs={"""files""": files}						)]
				_lowerCAmelCase			=[]
				for split_name, files in data_files.items():
					if isinstance(__UpperCAmelCase  ,  __UpperCAmelCase						):
						_lowerCAmelCase			=[files]
					_lowerCAmelCase			=[dl_manager.iter_files(__UpperCAmelCase						) for file in files]
					splits.append(datasets.SplitGenerator(name=__UpperCAmelCase  ,  gen_kwargs={"""files""": files}						)						)
				return splits



			def       _lowerCAmelCase	(							self  ,  __UpperCAmelCase						)				->  pa.Table:
				if self.config.features is not None:
					_lowerCAmelCase			=self.config.features.arrow_schema
					if all(not require_storage_cast(__UpperCAmelCase						) for feature in self.config.features.values()						):
						# cheaper cast
						_lowerCAmelCase			=pa_table.cast(__UpperCAmelCase						)
					else:
						# more expensive cast; allows str <-> int/float or str to Audio for example
						_lowerCAmelCase			=table_cast(__UpperCAmelCase  ,  __UpperCAmelCase						)
					return pa_table
				else:
					return pa_table.cast(pa.schema({"""text""": pa.string()}						)						)



			def       _lowerCAmelCase	(							self  ,  __UpperCAmelCase						)				->  List[Any]:
				_lowerCAmelCase			=list(self.config.features						) if self.config.features is not None else ["""text"""]
				for file_idx, file in enumerate(itertools.chain.from_iterable(__UpperCAmelCase						)						):
					# open in text mode, by default translates universal newlines ("\n", "\r\n" and "\r") into "\n"
					with open(__UpperCAmelCase  ,  encoding=self.config.encoding  ,  errors=self.config.errors						) as f:
						if self.config.sample_by == "line":
							_lowerCAmelCase			=0
							while True:
								_lowerCAmelCase			=f.read(self.config.chunksize						)
								if not batch:
									break
								batch += f.readline()  # finish current line
								# StringIO.readlines, by default splits only on "\n" (and keeps line breaks)
								_lowerCAmelCase			=StringIO(__UpperCAmelCase						).readlines()
								if not self.config.keep_linebreaks:
									_lowerCAmelCase			=[line.rstrip("""\n"""						) for line in batch]
								_lowerCAmelCase			=pa.Table.from_arrays([pa.array(__UpperCAmelCase						)]  ,  names=__UpperCAmelCase						)
								# Uncomment for debugging (will print the Arrow table size and elements)
								# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
								# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
								yield (file_idx, batch_idx), self._cast_table(__UpperCAmelCase						)
								batch_idx += 1
						elif self.config.sample_by == "paragraph":
							_lowerCAmelCase			=0
							_lowerCAmelCase			=""""""
							while True:
								_lowerCAmelCase			=f.read(self.config.chunksize						)
								if not new_batch:
									break
								batch += new_batch
								batch += f.readline()  # finish current line
								_lowerCAmelCase			=batch.split("""\n\n"""						)
								_lowerCAmelCase			=pa.Table.from_arrays(
								    [pa.array([example for example in batch[:-1] if example]						)]  ,  names=__UpperCAmelCase						)
								# Uncomment for debugging (will print the Arrow table size and elements)
								# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
								# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
								yield (file_idx, batch_idx), self._cast_table(__UpperCAmelCase						)
								batch_idx += 1
								_lowerCAmelCase			=batch[-1]
							if batch:
								_lowerCAmelCase			=pa.Table.from_arrays([pa.array([batch]						)]  ,  names=__UpperCAmelCase						)
								yield (file_idx, batch_idx), self._cast_table(__UpperCAmelCase						)
						elif self.config.sample_by == "document":
							_lowerCAmelCase			=f.read()
							_lowerCAmelCase			=pa.Table.from_arrays([pa.array([text]						)]  ,  names=__UpperCAmelCase						)
							yield file_idx, self._cast_table(__UpperCAmelCase						)





"""simple docstring"""


import os
import sys

from . import rsa_key_generator as rkg

__A 		= 128
__A 		= 256



def 					_lowerCamelCase(__UpperCamelCase					,				__UpperCamelCase = DEFAULT_BLOCK_SIZE )       ->				list[int]:
	_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 					_lowerCamelCase(__UpperCamelCase					,				__UpperCamelCase					,				__UpperCamelCase = DEFAULT_BLOCK_SIZE )       ->				str:
	_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 					_lowerCamelCase(__UpperCamelCase					,				__UpperCamelCase					,				__UpperCamelCase = DEFAULT_BLOCK_SIZE )       ->				list[int]:
	_lowerCAmelCase			=[]
	_lowerCAmelCase		,							_lowerCAmelCase			=key

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



def 					_lowerCamelCase(__UpperCamelCase					,				__UpperCamelCase					,				__UpperCamelCase					,				__UpperCamelCase = DEFAULT_BLOCK_SIZE					,				)       ->				str:
	_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 					_lowerCamelCase(__UpperCamelCase )       ->				tuple[int, int, int]:
	with open(__UpperCamelCase ) as fo:
		_lowerCAmelCase			=fo.read()
	_lowerCAmelCase		,							_lowerCAmelCase		,							_lowerCAmelCase			=content.split(""",""" )
	return (int(__UpperCamelCase ), int(__UpperCamelCase ), int(__UpperCamelCase ))



def 					_lowerCamelCase(__UpperCamelCase					,				__UpperCamelCase					,				__UpperCamelCase					,				__UpperCamelCase = DEFAULT_BLOCK_SIZE					,				)       ->				str:
	_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 					_lowerCamelCase(__UpperCamelCase					,				__UpperCamelCase )       ->				str:
	_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 					_lowerCamelCase()       ->				None:
	_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()



