



import argparse
import json
import os

import fairseq
import torch
from torch import nn

from transformers import (
    SpeechaTextaConfig,
    SpeechaTextaForCausalLM,
    SpeechaTextaTokenizer,
    SpeechEncoderDecoderConfig,
    SpeechEncoderDecoderModel,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaModel,
    logging,
)


logging.set_verbosity_info()
a      :  Tuple			     =			logging.get_logger(__name__)

a      :  List[Any]			     =			{
    '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',
    'w2v_model.layer_norm': 'feature_projection.layer_norm',
    'quantizer.weight_proj': 'quantizer.weight_proj',
    'quantizer.vars': 'quantizer.codevectors',
    'project_q': 'project_q',
    'final_proj': 'project_hid',
    'w2v_encoder.proj': 'lm_head',
    'mask_emb': 'masked_spec_embed',
}
a      :  int			     =			[
    'lm_head',
    'quantizer.weight_proj',
    'quantizer.codevectors',
    'project_q',
    'project_hid',
]







def  lowerCAmelCase_	(lowerCAmelCase__:		Dict		,						lowerCAmelCase__:		Union[str, Any]		,						lowerCAmelCase__:		List[str]		,						lowerCAmelCase__:		Union[str, Any]		,						lowerCAmelCase__:		Dict  ):





			"""simple docstring"""


			for attribute in key.split("""."""  ):
						UpperCAmelCase_:		Dict							      =     getattr(a__		,						a__  )

			if weight_type is not None:
						UpperCAmelCase_:		Dict							      =     getattr(a__		,						a__  ).shape
			else:
						UpperCAmelCase_:		List[Any]							      =     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":
						UpperCAmelCase_:		int							      =     value
			elif weight_type == "weight_g":
						UpperCAmelCase_:		Any							      =     value
			elif weight_type == "weight_v":
						UpperCAmelCase_:		Optional[int]							      =     value
			elif weight_type == "bias":
						UpperCAmelCase_:		Dict							      =     value
			else:
						UpperCAmelCase_:		Optional[int]							      =     value

			logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.'  )







def  lowerCAmelCase_	(lowerCAmelCase__:		Tuple		,						lowerCAmelCase__:		Optional[int]  ):





			"""simple docstring"""


			UpperCAmelCase_:		Union[str, Any]							      =     []
			UpperCAmelCase_:		str							      =     fairseq_model.state_dict()

			UpperCAmelCase_:		List[str]							      =     hf_model.feature_extractor

			# if encoder has different dim to decoder -> use proj_weight
			UpperCAmelCase_:		str							      =     None

			for name, value in fairseq_dict.items():
						UpperCAmelCase_:		List[Any]							      =     False
						if "conv_layers" in name:
									load_conv_layer(
									    a__		,						a__		,						a__		,						a__		,						hf_model.config.feat_extract_norm == """group"""		,						)
									UpperCAmelCase_:		Optional[int]							      =     True
						elif name.split("""."""  )[0] == "proj":
									UpperCAmelCase_:		List[Any]							      =     fairseq_model.proj
									UpperCAmelCase_:		Any							      =     True
						else:
									for key, mapped_key in MAPPING.items():
												if key in name or key.split("""w2v_model."""  )[-1] == name.split("""."""  )[0]:
															UpperCAmelCase_:		List[str]							      =     True
															if "*" in mapped_key:
																		UpperCAmelCase_:		Optional[Any]							      =     name.split(a__  )[0].split("""."""  )[-2]
																		UpperCAmelCase_:		Optional[int]							      =     mapped_key.replace("""*"""		,						a__  )
															if "weight_g" in name:
																		UpperCAmelCase_:		Union[str, Any]							      =     """weight_g"""
															elif "weight_v" in name:
																		UpperCAmelCase_:		Optional[Any]							      =     """weight_v"""
															elif "bias" in name:
																		UpperCAmelCase_:		str							      =     """bias"""
															elif "weight" in name:
																		UpperCAmelCase_:		str							      =     """weight"""
															else:
																		UpperCAmelCase_:		List[Any]							      =     None
															set_recursively(a__		,						a__		,						a__		,						a__		,						a__  )
												continue
						if not is_used:
									unused_weights.append(a__  )

			logger.warning(F'Unused weights: {unused_weights}'  )

			return proj_weight







def  lowerCAmelCase_	(lowerCAmelCase__:		Union[str, Any]		,						lowerCAmelCase__:		Union[str, Any]		,						lowerCAmelCase__:		Optional[Any]		,						lowerCAmelCase__:		int		,						lowerCAmelCase__:		Optional[int]  ):





			"""simple docstring"""


			UpperCAmelCase_:		str							      =     full_name.split("""conv_layers."""  )[-1]
			UpperCAmelCase_:		int							      =     name.split("""."""  )
			UpperCAmelCase_:		Optional[Any]							      =     int(items[0]  )
			UpperCAmelCase_:		Optional[Any]							      =     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.'
									)
									UpperCAmelCase_:		Optional[int]							      =     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.'
									)
									UpperCAmelCase_:		Dict							      =     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."
									)
									UpperCAmelCase_:		int							      =     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.'
									)
									UpperCAmelCase_:		str							      =     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_	(lowerCAmelCase__:		Optional[Any]  ):





			"""simple docstring"""


			UpperCAmelCase_      ,							UpperCAmelCase_:		int							      =     emb.weight.shape
			UpperCAmelCase_:		Optional[Any]							      =     nn.Linear(a__		,						a__		,						bias=a__  )
			UpperCAmelCase_:		Tuple							      =     emb.weight.data
			return lin_layer







def  lowerCAmelCase_	(lowerCAmelCase__:		Union[str, Any]  ):





			"""simple docstring"""


			with open(a__		,						"""r"""		,						encoding="""utf-8"""  ) as f:
						UpperCAmelCase_:		str							      =     f.readlines()
						UpperCAmelCase_:		Optional[Any]							      =     [line.split(""" """  )[0] for line in lines]

			UpperCAmelCase_:		Dict							      =     len(a__  )

			UpperCAmelCase_:		Tuple							      =     {
			    """<s>""": 0,
			    """<pad>""": 1,
			    """</s>""": 2,
			    """<unk>""": 3,
			}

			vocab_dict.update(dict(zip(a__		,						range(4		,						num_words + 4  )  )  )  )
			return vocab_dict







@torch.no_grad()
def  lowerCAmelCase_	(lowerCAmelCase__:		Dict		,						lowerCAmelCase__:		Optional[int]		,						lowerCAmelCase__:		List[str]		,						lowerCAmelCase__:		Any		,						lowerCAmelCase__:		Optional[Any]		,						lowerCAmelCase__:		Dict		,						lowerCAmelCase__:		Optional[int]		,						):





			"""simple docstring"""


			UpperCAmelCase_:		Dict							      =     WavaVecaConfig.from_pretrained(a__  )
			UpperCAmelCase_:		Dict							      =     SpeechaTextaConfig.from_pretrained(
			    a__		,						vocab_size=a__		,						decoder_layers=a__		,						do_stable_layer_norm=a__  )

			UpperCAmelCase_:		int							      =     WavaVecaFeatureExtractor(
			    feature_size=1		,						sampling_rate=1_6_0_0_0		,						padding_value=0		,						do_normalize=a__		,						return_attention_mask=a__		,						)

			UpperCAmelCase_      ,							UpperCAmelCase_      ,							UpperCAmelCase_:		Union[str, Any]							      =     fairseq.checkpoint_utils.load_model_ensemble_and_task(
			    [checkpoint_path]		,						arg_overrides={"""data""": """/""".join(dict_path.split("""/"""  )[:-1]  )}  )
			UpperCAmelCase_:		List[Any]							      =     model[0].eval()

			# set weights for wav2vec2 encoder
			UpperCAmelCase_:		Dict							      =     WavaVecaModel(a__  )
			UpperCAmelCase_:		Union[str, Any]							      =     recursively_load_weights_wavaveca(model.encoder		,						a__  )

			UpperCAmelCase_:		Tuple							      =     SpeechaTextaForCausalLM(a__  )
			UpperCAmelCase_      ,							UpperCAmelCase_:		Union[str, Any]							      =     hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict()		,						strict=a__  )

			# set output linear layer
			unexpected_keys.remove("""embed_out"""  )
			UpperCAmelCase_:		Dict							      =     nn.Parameter(model.decoder.embed_out.detach()  )

			# layer norm is init to identity matrix so leaving it is fine
			logger.warning(F'The following keys are missing when loading the decoder weights: {missing_keys}'  )
			logger.warning(F'The following keys are unexpected when loading the decoder weights: {unexpected_keys}'  )

			UpperCAmelCase_:		List[str]							      =     SpeechEncoderDecoderModel(encoder=a__		,						decoder=a__  )
			UpperCAmelCase_:		Optional[int]							      =     False

			# add projection layer
			UpperCAmelCase_:		Optional[int]							      =     nn.Parameter(projection_layer.weight  )
			UpperCAmelCase_:		List[Any]							      =     nn.Parameter(projection_layer.bias  )

			UpperCAmelCase_:		Tuple							      =     create_vocab_dict(a__  )

			with open(os.path.join(a__		,						"""vocab.json"""  )		,						"""w"""  ) as fp:
						json.dump(a__		,						a__  )

			UpperCAmelCase_:		List[Any]							      =     SpeechaTextaTokenizer(os.path.join(a__		,						"""vocab.json"""  )  )
			tokenizer.save_pretrained(a__  )

			UpperCAmelCase_:		Union[str, Any]							      =     hf_wavavec.config.to_dict()
			UpperCAmelCase_:		Optional[int]							      =     tokenizer.pad_token_id
			UpperCAmelCase_:		Any							      =     tokenizer.bos_token_id
			UpperCAmelCase_:		List[str]							      =     tokenizer.eos_token_id
			UpperCAmelCase_:		Tuple							      =     """speech_to_text_2"""
			UpperCAmelCase_:		Any							      =     """wav2vec2"""

			UpperCAmelCase_:		Any							      =     SpeechEncoderDecoderConfig.from_dict(a__  )

			hf_wavavec.save_pretrained(a__  )
			feature_extractor.save_pretrained(a__  )


if __name__ == "__main__":
	a      :  Union[str, Any]			     =			argparse.ArgumentParser()
	parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
	parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint')
	parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model')
	parser.add_argument(
	    '--encoder_config_path',
	    default='facebook/wav2vec2-large-lv60',
	    type=str,
	    help='Path to hf encoder wav2vec2 checkpoint config',
	)
	parser.add_argument(
	    '--decoder_config_path',
	    default='facebook/s2t-small-mustc-en-fr-st',
	    type=str,
	    help='Path to hf decoder s2t checkpoint config',
	)
	parser.add_argument('--vocab_size', default=10_224, type=int, help='Vocab size of decoder')
	parser.add_argument('--num_decoder_layers', default=7, type=int, help='Number of decoder layers')

	a      :  Optional[Any]			     =			parser.parse_args()
	convert_wavaveca_checkpoint(
	    args.checkpoint_path,
	    args.pytorch_dump_folder_path,
	    args.dict_path,
	    encoder_config_path=args.encoder_config_path,
	    decoder_config_path=args.decoder_config_path,
	    vocab_size=args.vocab_size,
	    num_decoder_layers=args.num_decoder_layers,
	)













import copy
import random

from transformers import CLIPTokenizer

class 							__SCREAMING_SNAKE_CASE       (  _a							):






							def __init__(    self	,			*__lowerCAmelCase	,			**__lowerCAmelCase	):
														super().__init__(*__lowerCAmelCase	,			**__lowerCAmelCase	)
														UpperCamelCase__					  =      {}






							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase	,			*__lowerCAmelCase	,			**__lowerCAmelCase	):
														UpperCamelCase__					  =      super().add_tokens(__lowerCAmelCase	,			*__lowerCAmelCase	,			**__lowerCAmelCase	)
														if num_added_tokens == 0:
																					raise ValueError(
																					    f"""The tokenizer already contains the token {placeholder_token}. Please pass a different"""
																					    """ `placeholder_token` that is not already in the tokenizer."""	)






							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase	,			*__lowerCAmelCase	,			__lowerCAmelCase=1	,			**__lowerCAmelCase	):
														UpperCamelCase__					  =      []
														if num_vec_per_token == 1:
																					self.try_adding_tokens(__lowerCAmelCase	,			*__lowerCAmelCase	,			**__lowerCAmelCase	)
																					output.append(__lowerCAmelCase	)
														else:
																					UpperCamelCase__					  =      []
																					for i in range(__lowerCAmelCase	):
																												UpperCamelCase__					  =      placeholder_token + f"""_{i}"""
																												self.try_adding_tokens(__lowerCAmelCase	,			*__lowerCAmelCase	,			**__lowerCAmelCase	)
																												output.append(__lowerCAmelCase	)
        # handle cases where there is a new placeholder token that contains the current placeholder token but is larger
														for token in self.token_map:
																					if token in placeholder_token:
																												raise ValueError(
																												    f"""The tokenizer already has placeholder token {token} that can get confused with"""
																												    f""" {placeholder_token}keep placeholder tokens independent"""	)
														UpperCamelCase__					  =      output






							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase	,			__lowerCAmelCase=False	,			__lowerCAmelCase=1.0	):
														if isinstance(__lowerCAmelCase	,			__lowerCAmelCase	):
																					UpperCamelCase__					  =      []
																					for i in range(len(__lowerCAmelCase	)	):
																												output.append(self.replace_placeholder_tokens_in_text(text[i]	,			vector_shuffle=__lowerCAmelCase	)	)
																					return output
														for placeholder_token in self.token_map:
																					if placeholder_token in text:
																												UpperCamelCase__					  =      self.token_map[placeholder_token]
																												UpperCamelCase__					  =      tokens[: 1 + int(len(__lowerCAmelCase	) * prop_tokens_to_load	)]
																												if vector_shuffle:
																																			UpperCamelCase__					  =      copy.copy(__lowerCAmelCase	)
																																			random.shuffle(__lowerCAmelCase	)
																												UpperCamelCase__					  =      text.replace(__lowerCAmelCase	,			""" """.join(__lowerCAmelCase	)	)
														return text






							def __call__(    self	,			__lowerCAmelCase	,			*__lowerCAmelCase	,			__lowerCAmelCase=False	,			__lowerCAmelCase=1.0	,			**__lowerCAmelCase	):
														return super().__call__(
														    self.replace_placeholder_tokens_in_text(
														        __lowerCAmelCase	,			vector_shuffle=__lowerCAmelCase	,			prop_tokens_to_load=__lowerCAmelCase	)	,			*__lowerCAmelCase	,			**__lowerCAmelCase	,			)







							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase	,			*__lowerCAmelCase	,			__lowerCAmelCase=False	,			__lowerCAmelCase=1.0	,			**__lowerCAmelCase	):
														return super().encode(
														    self.replace_placeholder_tokens_in_text(
														        __lowerCAmelCase	,			vector_shuffle=__lowerCAmelCase	,			prop_tokens_to_load=__lowerCAmelCase	)	,			*__lowerCAmelCase	,			**__lowerCAmelCase	,			)




