






import argparse

import torch
from saprl.hub import distilhubert

from transformers import HubertConfig, HubertModel, WavaVecaFeatureExtractor, logging


logging.set_verbosity_info()
lowerCamelCase_		  =						logging.get_logger(__name__)

lowerCamelCase_		  =						{
    """post_extract_proj""": """feature_projection.projection""",
    """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""",
    """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""",
    """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""",
    """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""",
    """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""",
    """self_attn_layer_norm""": """encoder.layers.*.layer_norm""",
    """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""",
    """fc2""": """encoder.layers.*.feed_forward.output_dense""",
    """final_layer_norm""": """encoder.layers.*.final_layer_norm""",
    """encoder.layer_norm""": """encoder.layer_norm""",
    """mask_emb""": """masked_spec_embed""",
}
def   lowerCamelCase      (		a_				,		a_				,		a_				,		a_				,		a_			)			->    List[Any]:
							for attribute in key.split('.'			):
														lowerCAmelCase_       		=  getattr(a_				,		a_			)

							if weight_type is not None:
														lowerCAmelCase_       		=  getattr(a_				,		a_			).shape
							else:
														lowerCAmelCase_       		=  hf_pointer.shape

							assert hf_shape == value.shape, (
							    F'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'''
							    F''' {value.shape} for {full_name}'''
							)

							if weight_type == "weight":
														lowerCAmelCase_       		=  value
							elif weight_type == "weight_g":
														lowerCAmelCase_       		=  value
							elif weight_type == "weight_v":
														lowerCAmelCase_       		=  value
							elif weight_type == "bias":
														lowerCAmelCase_       		=  value
							else:
														lowerCAmelCase_       		=  value

							logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.'''			)
def   lowerCamelCase      (		a_				,		a_			)			->    int:
							lowerCAmelCase_       		=  []
							lowerCAmelCase_       		=  fairseq_model.state_dict()

							lowerCAmelCase_       		=  hf_model.feature_extractor

							for name, value in fairseq_dict.items():
														lowerCAmelCase_       		=  False
														if "conv_layers" in name:
																					load_conv_layer(
																					    a_				,		a_				,		a_				,		a_				,		hf_model.config.feat_extract_norm == 'group'				,		)
																					lowerCAmelCase_       		=  True
														else:
																					for key, mapped_key in MAPPING.items():
																												lowerCAmelCase_       		=  mapped_key

																												if key in name:
																																			lowerCAmelCase_       		=  True
																																			if "*" in mapped_key:
																																										lowerCAmelCase_       		=  name.split(a_			)[0].split('.'			)[-2]
																																										lowerCAmelCase_       		=  mapped_key.replace('*'				,		a_			)
																																			if "weight_g" in name:
																																										lowerCAmelCase_       		=  'weight_g'
																																			elif "weight_v" in name:
																																										lowerCAmelCase_       		=  'weight_v'
																																			elif "weight" in name:
																																										lowerCAmelCase_       		=  'weight'
																																			elif "bias" in name:
																																										lowerCAmelCase_       		=  'bias'
																																			else:
																																										lowerCAmelCase_       		=  None
																																			set_recursively(a_				,		a_				,		a_				,		a_				,		a_			)
																												continue
														if not is_used:
																					unused_weights.append(a_			)

							logger.warning(F'''Unused weights: {unused_weights}'''			)
def   lowerCamelCase      (		a_				,		a_				,		a_				,		a_				,		a_			)			->    Union[str, Any]:
							lowerCAmelCase_       		=  full_name.split('conv_layers.'			)[-1]
							lowerCAmelCase_       		=  name.split('.'			)
							lowerCAmelCase_       		=  int(items[0]			)
							lowerCAmelCase_       		=  int(items[1]			)

							if type_id == 0:
														if "bias" in name:
																					assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
																					    F'''{full_name} has size {value.shape}, but'''
																					    F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
																					)
																					lowerCAmelCase_       		=  value
																					logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''			)
														elif "weight" in name:
																					assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
																					    F'''{full_name} has size {value.shape}, but'''
																					    F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
																					)
																					lowerCAmelCase_       		=  value
																					logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''			)
							elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
														if "bias" in name:
																					assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
																					    F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
																					    " found."
																					)
																					lowerCAmelCase_       		=  value
																					logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''			)
														elif "weight" in name:
																					assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
																					    F'''{full_name} has size {value.shape}, but'''
																					    F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
																					)
																					lowerCAmelCase_       		=  value
																					logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''			)
							else:
														unused_weights.append(a_			)
def   lowerCamelCase      (		a_			)			->    str:
							lowerCAmelCase_       		=  HubertConfig()
							lowerCAmelCase_       		=  model.config

							lowerCAmelCase_       		=  fs_config.activation_dropout
							lowerCAmelCase_       		=  False
							lowerCAmelCase_       		=  fs_config.attention_dropout
							lowerCAmelCase_       		=  False
							lowerCAmelCase_       		=  eval(fs_config.extractor_conv_feature_layers			)
							lowerCAmelCase_       		=  [x[0] for x in conv_layers]
							lowerCAmelCase_       		=  [x[1] for x in conv_layers]
							lowerCAmelCase_       		=  [x[2] for x in conv_layers]
							lowerCAmelCase_       		=  'gelu'
							lowerCAmelCase_       		=  'layer' if fs_config.extractor_mode == 'layer_norm' else 'group'
							lowerCAmelCase_       		=  False
							lowerCAmelCase_       		=  0.0
							lowerCAmelCase_       		=  0.0
							lowerCAmelCase_       		=  fs_config.activation_fn
							lowerCAmelCase_       		=  fs_config.dropout
							lowerCAmelCase_       		=  fs_config.encoder_embed_dim
							lowerCAmelCase_       		=  0.02
							lowerCAmelCase_       		=  fs_config.encoder_ffn_embed_dim
							lowerCAmelCase_       		=  1e-5
							lowerCAmelCase_       		=  0.0
							lowerCAmelCase_       		=  fs_config.encoder_attention_heads
							lowerCAmelCase_       		=  fs_config.conv_pos_groups
							lowerCAmelCase_       		=  fs_config.conv_pos
							lowerCAmelCase_       		=  len(a_			)
							lowerCAmelCase_       		=  fs_config.encoder_layers

							return config
@torch.no_grad()
def   lowerCamelCase      (		a_				,		a_=None			)			->    Union[str, Any]:
							lowerCAmelCase_       		=  distilhubert().model.model

							if config_path is not None:
														lowerCAmelCase_       		=  HubertConfig.from_pretrained(a_			)
							else:
														lowerCAmelCase_       		=  convert_config(a_			)
							lowerCAmelCase_       		=  model.eval()

							lowerCAmelCase_       		=  WavaVecaFeatureExtractor(
							    feature_size=1				,		sampling_rate=16_000				,		padding_value=0				,		do_normalize=a_				,		return_attention_mask=a_				,		)
							lowerCAmelCase_       		=  HubertModel(a_			)

							recursively_load_weights(a_				,		a_			)

							feature_extractor.save_pretrained(a_			)
							hf_model.save_pretrained(a_			)


if __name__ == "__main__":
		lowerCamelCase_		  =						argparse.ArgumentParser()
		parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
		parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
		lowerCamelCase_		  =						parser.parse_args()
		convert_hubert_checkpoint(args.pytorch_dump_folder_path, args.config_path)











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



