






import json
import os
from collections.abc import Mapping
from typing import Dict, List, Optional, Union

import numpy as np
import torch

from .imports import is_safetensors_available
def   lowerCamelCase      (		a_				,		a_				,		a_				,		a_=None			)			->    str:
							lowerCAmelCase_       		=  None
							# Check the string instead of the dtype to be compatible with versions of PyTorch that don't have bfloat16.
							if str(weight.dtype			) == "torch.bfloat16":
														# Need to reinterpret the underlined data as int16 since NumPy does not handle bfloat16s.
														lowerCAmelCase_       		=  weight.view(torch.intaa			)
														lowerCAmelCase_       		=  'bfloat16'
							lowerCAmelCase_       		=  weight.cpu().numpy()
							lowerCAmelCase_       		=  os.path.join(UpperCamelCase_				,		F'''{weight_name}.dat'''			)
							if index is not None:
														if dtype is None:
																					lowerCAmelCase_       		=  str(array.dtype			)
														lowerCAmelCase_       		=  {'dtype': dtype, 'shape': list(array.shape			)}
							if array.ndim == 0:
														lowerCAmelCase_       		=  array[None]
							lowerCAmelCase_       		=  np.memmap(UpperCamelCase_				,		dtype=array.dtype				,		mode='w+'				,		shape=array.shape			)
							lowerCAmelCase_       		=  array[:]
							file_array.flush()
							return index
def   lowerCamelCase      (		a_				,		a_			)			->    str:
							lowerCAmelCase_       		=  tuple(weight_info['shape']			)
							if shape == ():
														# NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor
														lowerCAmelCase_       		=  (1,)

							lowerCAmelCase_       		=  weight_info['dtype']
							if dtype == "bfloat16":
														# NumPy does not support bfloat16 so this was saved as a int16
														lowerCAmelCase_       		=  'int16'

							lowerCAmelCase_       		=  np.memmap(UpperCamelCase_				,		dtype=UpperCamelCase_				,		shape=UpperCamelCase_				,		mode='r'			)

							if len(weight_info['shape']			) == 0:
														lowerCAmelCase_       		=  weight[0]
							lowerCAmelCase_       		=  torch.tensor(UpperCamelCase_			)
							if weight_info["dtype"] == "bfloat16":
														lowerCAmelCase_       		=  weight.view(torch.bfloataa			)

							return weight
def   lowerCamelCase      (		a_				,		a_			)			->    Optional[int]:






							if index is None or len(UpperCamelCase_			) == 0:
														# Nothing to save
														return

							lowerCAmelCase_       		=  os.path.join(UpperCamelCase_				,		'index.json'			)
							if os.path.isfile(UpperCamelCase_			):
														with open(UpperCamelCase_				,		'r'				,		encoding='utf-8'			) as f:
																					lowerCAmelCase_       		=  json.load(UpperCamelCase_			)
							else:
														lowerCAmelCase_       		=  {}
							current_index.update(UpperCamelCase_			)

							with open(UpperCamelCase_				,		'w'				,		encoding='utf-8'			) as f:
														json.dump(UpperCamelCase_				,		UpperCamelCase_				,		indent=2			)
def   lowerCamelCase      (		a_				,		a_			)			->    List[Any]:
							os.makedirs(UpperCamelCase_				,		exist_ok=UpperCamelCase_			)
							lowerCAmelCase_       		=  {}
							for name, parameter in state_dict.items():
														lowerCAmelCase_       		=  offload_weight(UpperCamelCase_				,		UpperCamelCase_				,		UpperCamelCase_				,		index=UpperCamelCase_			)

							# Update index
							save_offload_index(UpperCamelCase_				,		UpperCamelCase_			)




class 							a_				(		snake_case__	):


							'''simple docstring'''






							def __init__(	self    ,    lowercase_    ,    lowercase_     )      ->      Optional[Any]:
														'''simple docstring'''

														lowerCAmelCase_       		=  dataset
														lowerCAmelCase_       		=  prefix

							def __getitem__(	self    ,    lowercase_     )      ->      Union[str, Any]:
														'''simple docstring'''

														return self.dataset[f'''{self.prefix}{key}''']

							def __iter__(	self     )      ->      Optional[Any]:
														'''simple docstring'''

														return iter([key for key in self.dataset if key.startswith(self.prefix     )]     )






							def __len__(	self     )      ->      Tuple:
														'''simple docstring'''

														return len(self.dataset     )




class 							a_				(		snake_case__	):


							'''simple docstring'''






							def __init__(	self    ,    lowercase_ = None    ,    lowercase_ = None    ,    lowercase_ = None    ,    lowercase_=None    ,    )      ->      str:
														'''simple docstring'''

														if state_dict is None and save_folder is None:
																					raise ValueError('Need either a `state_dict` or a `save_folder` containing offloaded weights.'     )

														lowerCAmelCase_       		=  {} if state_dict is None else state_dict
														lowerCAmelCase_       		=  save_folder
														if index is None and save_folder is not None:
																					with open(os.path.join(__snake_case    ,    'index.json'     )     ) as f:
																												lowerCAmelCase_       		=  json.load(__snake_case     )
														lowerCAmelCase_       		=  {} if index is None else index
														lowerCAmelCase_       		=  list(self.state_dict.keys()     )
														self.all_keys.extend([key for key in self.index if key not in self.all_keys]     )
														lowerCAmelCase_       		=  device

							def __getitem__(	self    ,    lowercase_     )      ->      int:
														'''simple docstring'''

														if key in self.state_dict:
																					return self.state_dict[key]
														lowerCAmelCase_       		=  self.index[key]
														if weight_info.get('safetensors_file'     ) is not None:
																					if not is_safetensors_available():
																												raise ImportError('These offloaded weights require the use of safetensors: `pip install safetensors`.'     )

																					from safetensors import safe_open

																					lowerCAmelCase_       		=  'cpu' if self.device is None else self.device
																					with safe_open(weight_info['safetensors_file']    ,    framework='pt'    ,    device=__snake_case     ) as f:
																												lowerCAmelCase_       		=  f.get_tensor(weight_info.get('weight_name'    ,    __snake_case     )     )

																					if "dtype" in weight_info:
																												return tensor.to(getattr(__snake_case    ,    weight_info['dtype']     )     )
																					else:
																												return tensor

														lowerCAmelCase_       		=  os.path.join(self.save_folder    ,    f'''{key}.dat'''     )
														return load_offloaded_weight(__snake_case    ,    __snake_case     )

							def __iter__(	self     )      ->      Any:
														'''simple docstring'''

														return iter(self.all_keys     )






							def __len__(	self     )      ->      int:
														'''simple docstring'''

														return len(self.all_keys     )


def   lowerCamelCase      (		a_				,		a_			)			->    Any:
							lowerCAmelCase_       		=  {}
							for module_name in submodule_names:
														# We want to catch module_name parameter (module_name.xxx) or potentially module_name, but not any of the
														# submodules that could being like module_name (transformers.h.1 and transformers.h.10 for instance)
														result.update(
														    {
														        key: param
														        for key, param in state_dict.items()
														        if key == module_name or key.startswith(module_name + '.'			)
														    }			)
							return result











from __future__ import annotations

from string import ascii_letters
def   lowerCamelCase      (		a_				,		a_				,		a_ = None			)			->    str:
							lowerCAmelCase_       		=  alphabet or ascii_letters

							# The final result string
							lowerCAmelCase_       		=  ''

							for character in input_string:
														if character not in alpha:
																					# Append without encryption if character is not in the alphabet
																					result += character
														else:
																					# Get the index of the new key and make sure it isn't too large
																					lowerCAmelCase_       		=  (alpha.index(a_			) + key) % len(a_			)

																					# Append the encoded character to the alphabet
																					result += alpha[new_key]

							return result
def   lowerCamelCase      (		a_				,		a_				,		a_ = None			)			->    str:
							key *= -1

							return encrypt(a_				,		a_				,		a_			)
def   lowerCamelCase      (		a_				,		a_ = None			)			->    dict[int, str]:
							lowerCAmelCase_       		=  alphabet or ascii_letters

							# To store data on all the combinations
							lowerCAmelCase_       		=  {}

							# Cycle through each combination
							for key in range(1				,		len(a_			) + 1			):
														# Decrypt the message and store the result in the data
														lowerCAmelCase_       		=  decrypt(a_				,		a_				,		a_			)

							return brute_force_data


if __name__ == "__main__":
		while True:
				print(f'''\n{"-" * 1_0}\n Menu\n{"-" * 1_0}''')
				print(*["""1.Encrypt""", """2.Decrypt""", """3.BruteForce""", """4.Quit"""], sep="""\n""")

				# get user input
				lowerCamelCase_		  =						input("""\nWhat would you like to do?: """).strip() or """4"""

				# run functions based on what the user chose
				if choice not in ("1", "2", "3", "4"):
						print("""Invalid choice, please enter a valid choice""")
				elif choice == "1":
						lowerCamelCase_		  =						input("""Please enter the string to be encrypted: """)
						lowerCamelCase_		  =						int(input("""Please enter off-set: """).strip())

						print(encrypt(input_string, key))
				elif choice == "2":
						lowerCamelCase_		  =						input("""Please enter the string to be decrypted: """)
						lowerCamelCase_		  =						int(input("""Please enter off-set: """).strip())

						print(decrypt(input_string, key))
				elif choice == "3":
						lowerCamelCase_		  =						input("""Please enter the string to be decrypted: """)
						lowerCamelCase_		  =						brute_force(input_string)

						for key, value in brute_force_data.items():
								print(f'''Key: {key} | Message: {value}''')

				elif choice == "4":
						print("""Goodbye.""")
						break



