





"""simple docstring"""






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()
__UpperCAmelCase						=			logging.get_logger(__name__)

__UpperCAmelCase						=			{
    '''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''',
}
__UpperCAmelCase						=			[
    '''lm_head''',
    '''quantizer.weight_proj''',
    '''quantizer.codevectors''',
    '''project_q''',
    '''project_hid''',
]






def      lowercase__ (					lowerCAmelCase__   :			Dict							,			lowerCAmelCase__   :			Optional[int]							,			lowerCAmelCase__   :			str							,			lowerCAmelCase__   :			Optional[Any]							,			lowerCAmelCase__   :			Union[str, Any]			)    ->			Optional[Any]:



			'''simple docstring'''
			for attribute in key.split("."			):
						a__  :	Dict		 =			getattr(lowerCAmelCase__							,			lowerCAmelCase__			)

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

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






def      lowercase__ (					lowerCAmelCase__   :			int							,			lowerCAmelCase__   :			List[Any]			)    ->			Optional[int]:



			'''simple docstring'''
			a__  :	Optional[Any]		 =			[]
			a__  :	Dict		 =			fairseq_model.state_dict()

			a__  :	List[Any]		 =			hf_model.feature_extractor

			# if encoder has different dim to decoder -> use proj_weight
			a__  :	Optional[Any]		 =			None

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

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

			return proj_weight






def      lowercase__ (					lowerCAmelCase__   :			Optional[Any]							,			lowerCAmelCase__   :			Dict							,			lowerCAmelCase__   :			Union[str, Any]							,			lowerCAmelCase__   :			Optional[int]							,			lowerCAmelCase__   :			List[Any]			)    ->			Union[str, Any]:



			'''simple docstring'''
			a__  :	List[str]		 =			full_name.split("conv_layers."			)[-1]
			a__  :	Optional[Any]		 =			name.split("."			)
			a__  :	List[str]		 =			int(items[0]			)
			a__  :	Union[str, 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."
									)
									a__  :	List[Any]		 =			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."
									)
									a__  :	Any		 =			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."
									)
									a__  :	Tuple		 =			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."
									)
									a__  :	Union[str, Any]		 =			value
									logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."			)
			else:
						unused_weights.append(lowerCAmelCase__			)






def      lowercase__ (					lowerCAmelCase__   :			Union[str, Any]			)    ->			Any:



			'''simple docstring'''
			a__ ,	a__  :	str		 =			emb.weight.shape
			a__  :	Any		 =			nn.Linear(lowerCAmelCase__							,			lowerCAmelCase__							,			bias=lowerCAmelCase__			)
			a__  :	List[str]		 =			emb.weight.data
			return lin_layer






def      lowercase__ (					lowerCAmelCase__   :			Tuple			)    ->			int:



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

			a__  :	Optional[int]		 =			len(lowerCAmelCase__			)

			a__  :	Optional[Any]		 =			{
			    "<s>": 0,
			    "<pad>": 1,
			    "</s>": 2,
			    "<unk>": 3,
			}

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






@torch.no_grad()
def      lowercase__ (					lowerCAmelCase__   :			Any							,			lowerCAmelCase__   :			int							,			lowerCAmelCase__   :			Optional[Any]							,			lowerCAmelCase__   :			Union[str, Any]							,			lowerCAmelCase__   :			Optional[int]							,			lowerCAmelCase__   :			List[Any]							,			lowerCAmelCase__   :			int							,			)    ->			Tuple:



			'''simple docstring'''
			a__  :	Any		 =			WavaVecaConfig.from_pretrained(lowerCAmelCase__			)
			a__  :	Union[str, Any]		 =			SpeechaTextaConfig.from_pretrained(
			    lowerCAmelCase__							,			vocab_size=lowerCAmelCase__							,			decoder_layers=lowerCAmelCase__							,			do_stable_layer_norm=lowerCAmelCase__			)

			a__  :	Optional[Any]		 =			WavaVecaFeatureExtractor(
			    feature_size=1							,			sampling_rate=1_6_0_0_0							,			padding_value=0							,			do_normalize=lowerCAmelCase__							,			return_attention_mask=lowerCAmelCase__							,			)

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

			# set weights for wav2vec2 encoder
			a__  :	int		 =			WavaVecaModel(lowerCAmelCase__			)
			a__  :	Tuple		 =			recursively_load_weights_wavaveca(model.encoder							,			lowerCAmelCase__			)

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

			# set output linear layer
			unexpected_keys.remove("embed_out"			)
			a__  :	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}"			)

			a__  :	Optional[Any]		 =			SpeechEncoderDecoderModel(encoder=lowerCAmelCase__							,			decoder=lowerCAmelCase__			)
			a__  :	List[str]		 =			False

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

			a__  :	Any		 =			create_vocab_dict(lowerCAmelCase__			)

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

			a__  :	Optional[int]		 =			SpeechaTextaTokenizer(os.path.join(lowerCAmelCase__							,			"vocab.json"			)			)
			tokenizer.save_pretrained(lowerCAmelCase__			)

			a__  :	int		 =			hf_wavavec.config.to_dict()
			a__  :	Any		 =			tokenizer.pad_token_id
			a__  :	Optional[int]		 =			tokenizer.bos_token_id
			a__  :	int		 =			tokenizer.eos_token_id
			a__  :	Optional[Any]		 =			"speech_to_text_2"
			a__  :	Dict		 =			"wav2vec2"

			a__  :	Any		 =			SpeechEncoderDecoderConfig.from_dict(lowerCAmelCase__			)

			hf_wavavec.save_pretrained(lowerCAmelCase__			)
			feature_extractor.save_pretrained(lowerCAmelCase__			)


if __name__ == "__main__":
		__UpperCAmelCase						=			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=1_0224, type=int, help='''Vocab size of decoder''')
		parser.add_argument('''--num_decoder_layers''', default=7, type=int, help='''Number of decoder layers''')

		__UpperCAmelCase						=			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,
		)






"""simple docstring"""






import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import SPIECE_UNDERLINE, logging


__UpperCAmelCase						=			logging.get_logger(__name__)

__UpperCAmelCase						=			{'''vocab_file''': '''spiece.model'''}

__UpperCAmelCase						=			{
    '''vocab_file''': {
        '''TsinghuaAI/CPM-Generate''': '''https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model''',
    }
}



class 					__UpperCAmelCase							(						_UpperCamelCase  ):
				def __init__(		self    :			str	, a_    :			Dict	, a_    :			List[str]=False	, a_    :			Any=True	, a_    :			int=False	, a_    :			Union[str, Any]="<s>"	, a_    :			Optional[int]="</s>"	, a_    :			int="<unk>"	, a_    :			List[Any]="<sep>"	, a_    :			Dict="<pad>"	, a_    :			Any="<cls>"	, a_    :			Optional[Any]="<mask>"	, a_    :			int=["<eop>", "<eod>"]	, a_    :			Optional[Dict[str, Any]] = None	, **a_    :			int	, )	->	None:



							'''simple docstring'''



							a__  :	List[str]		 =			AddedToken(a_	, lstrip=a_	, rstrip=a_    ) if isinstance(a_	, a_    ) else mask_token

							a__  :	List[str]		 =			{} if sp_model_kwargs is None else sp_model_kwargs

							super().__init__(
							    do_lower_case=a_	, remove_space=a_	, keep_accents=a_	, bos_token=a_	, eos_token=a_	, unk_token=a_	, sep_token=a_	, pad_token=a_	, cls_token=a_	, mask_token=a_	, additional_special_tokens=a_	, sp_model_kwargs=self.sp_model_kwargs	, **a_	, )

							a__  :	Union[str, Any]		 =			3

							a__  :	Dict		 =			do_lower_case
							a__  :	Union[str, Any]		 =			remove_space
							a__  :	int		 =			keep_accents
							a__  :	str		 =			vocab_file

							a__  :	str		 =			spm.SentencePieceProcessor(**self.sp_model_kwargs    )
							self.sp_model.Load(a_    )

							try:
										import jieba
							except ModuleNotFoundError as error:
										raise error.__class__(
										    "You need to install jieba to use CpmTokenizer or CpmTokenizerFast. "
										    "See https://pypi.org/project/jieba/ for installation."    )
							a__  :	Optional[int]		 =			jieba
							a__  :	Optional[int]		 =			str.maketrans(" \n"	, "\u2582\u2583"    )
				@property
				# Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
				def       UpperCAmelCase      (		self    :			Union[str, Any]    )	->	str:



							'''simple docstring'''



							return len(self.sp_model    )
				def       UpperCAmelCase      (		self    :			Dict    )	->	Union[str, Any]:



							'''simple docstring'''



							a__  :	Optional[int]		 =			{self.convert_ids_to_tokens(a_    ): i for i in range(self.vocab_size    )}
							vocab.update(self.added_tokens_encoder    )
							return vocab
				def __getstate__(		self    :			Tuple    )	->	List[str]:



							'''simple docstring'''



							a__  :	Tuple		 =			self.__dict__.copy()
							a__  :	Union[str, Any]		 =			None
							return state
				def __setstate__(		self    :			Tuple	, a_    :			int    )	->	List[str]:



							'''simple docstring'''



							a__  :	Any		 =			d

							# for backward compatibility
							if not hasattr(self	, "sp_model_kwargs"    ):
										a__  :	str		 =			{}

							a__  :	List[str]		 =			spm.SentencePieceProcessor(**self.sp_model_kwargs    )
							self.sp_model.Load(self.vocab_file    )
				def       UpperCAmelCase      (		self    :			List[Any]	, a_    :			Optional[Any]    )	->	List[str]:



							'''simple docstring'''



							if self.remove_space:
										a__  :	Union[str, Any]		 =			" ".join(inputs.strip().split()    )
							else:
										a__  :	Optional[Any]		 =			inputs
							a__  :	List[str]		 =			outputs.replace("``"	, "\""    ).replace("''"	, "\""    )

							if not self.keep_accents:
										a__  :	Union[str, Any]		 =			unicodedata.normalize("NFKD"	, a_    )
										a__  :	Union[str, Any]		 =			"".join([c for c in outputs if not unicodedata.combining(a_    )]    )
							if self.do_lower_case:
										a__  :	List[Any]		 =			outputs.lower()

							return outputs
				def       UpperCAmelCase      (		self    :			Any	, a_    :			str    )	->	List[str]:



							'''simple docstring'''



							a__  :	Optional[Any]		 =			self.preprocess_text(a_    )
							a__  :	Dict		 =			self.sp_model.encode(a_	, out_type=a_    )
							a__  :	Optional[Any]		 =			[]
							for piece in pieces:
										if len(a_    ) > 1 and piece[-1] == str(","    ) and piece[-2].isdigit():
													a__  :	Optional[Any]		 =			self.sp_model.EncodeAsPieces(piece[:-1].replace(a_	, ""    )    )
													if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
																if len(cur_pieces[0]    ) == 1:
																			a__  :	List[str]		 =			cur_pieces[1:]
																else:
																			a__  :	List[str]		 =			cur_pieces[0][1:]
													cur_pieces.append(piece[-1]    )
													new_pieces.extend(a_    )
										else:
													new_pieces.append(a_    )

							return new_pieces
				def       UpperCAmelCase      (		self    :			int	, a_    :			Dict    )	->	int:



							'''simple docstring'''



							return self.sp_model.PieceToId(a_    )
				def       UpperCAmelCase      (		self    :			Dict	, a_    :			Tuple    )	->	List[Any]:



							'''simple docstring'''



							return self.sp_model.IdToPiece(a_    )
				def       UpperCAmelCase      (		self    :			Union[str, Any]	, a_    :			List[Any]    )	->	str:



							'''simple docstring'''



							a__  :	Optional[Any]		 =			"".join(a_    ).replace(a_	, " "    ).strip()
							return out_string
				def       UpperCAmelCase      (		self    :			str	, a_    :			List[int]	, a_    :			Optional[List[int]] = None    )	->	List[int]:



							'''simple docstring'''



							a__  :	List[Any]		 =			[self.sep_token_id]
							a__  :	int		 =			[self.cls_token_id]
							if token_ids_a is None:
										return token_ids_a + sep + cls
							return token_ids_a + sep + token_ids_a + sep + cls
				def       UpperCAmelCase      (		self    :			int	, a_    :			List[int]	, a_    :			Optional[List[int]] = None	, a_    :			bool = False    )	->	List[int]:



							'''simple docstring'''



							if already_has_special_tokens:
										return super().get_special_tokens_mask(
										    token_ids_a=a_	, token_ids_a=a_	, already_has_special_tokens=a_    )

							if token_ids_a is not None:
										return ([0] * len(a_    )) + [1] + ([0] * len(a_    )) + [1, 1]
							return ([0] * len(a_    )) + [1, 1]
				def       UpperCAmelCase      (		self    :			List[Any]	, a_    :			List[int]	, a_    :			Optional[List[int]] = None    )	->	List[int]:



							'''simple docstring'''



							a__  :	List[str]		 =			[self.sep_token_id]
							a__  :	Tuple		 =			[2]

							if token_ids_a is None:
										return len(token_ids_a + sep    ) * [0] + cls_segment_id
							return len(token_ids_a + sep    ) * [0] + len(token_ids_a + sep    ) * [1] + cls_segment_id
				def       UpperCAmelCase      (		self    :			Dict	, a_    :			str	, a_    :			Optional[str] = None    )	->	Tuple[str]:



							'''simple docstring'''



							if not os.path.isdir(a_    ):
										logger.error(F"Vocabulary path ({save_directory}) should be a directory"    )
										return
							a__  :	Optional[int]		 =			os.path.join(
							    a_	, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]    )

							if os.path.abspath(self.vocab_file    ) != os.path.abspath(a_    ) and os.path.isfile(self.vocab_file    ):
										copyfile(self.vocab_file	, a_    )
							elif not os.path.isfile(self.vocab_file    ):
										with open(a_	, "wb"    ) as fi:
													a__  :	int		 =			self.sp_model.serialized_model_proto()
													fi.write(a_    )

							return (out_vocab_file,)






				def       UpperCAmelCase      (		self    :			str	, *a_    :			Union[str, Any]	, **a_    :			Any    )	->	int:



							'''simple docstring'''



							a__  :	Optional[int]		 =			super()._decode(*a_	, **a_    )
							a__  :	Tuple		 =			text.replace(" "	, ""    ).replace("\u2582"	, " "    ).replace("\u2583"	, "\n"    )
							return text