


import argparse

import fairseq
import torch
from torch import nn

from transformers import (
    MBartaaTokenizer,
    MBartConfig,
    MBartForCausalLM,
    SpeechEncoderDecoderConfig,
    SpeechEncoderDecoderModel,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaModel,
    logging,
)


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

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






def      _A				(UpperCamelCase		:      int      ,			UpperCamelCase		:      Any      ,			UpperCamelCase		:      Optional[Any]      ,			UpperCamelCase		:      List[Any]      ,			UpperCamelCase		:      Dict )  ->int:



			'''simple docstring'''







			for attribute in key.split(""".""" ):
						lowerCamelCase__ :      str								=		getattr(UpperCamelCase      ,			UpperCamelCase )

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

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






def      _A				(UpperCamelCase		:      str      ,			UpperCamelCase		:      Any )  ->Any:



			'''simple docstring'''







			lowerCamelCase__ :      Dict								=		[]
			lowerCamelCase__ :      int								=		fairseq_model.state_dict()

			lowerCamelCase__ :      Any								=		hf_model.feature_extractor
			lowerCamelCase__ :      Dict								=		hf_model.adapter

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

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






def      _A				(UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      Tuple      ,			UpperCamelCase		:      Dict      ,			UpperCamelCase		:      Union[str, Any]      ,			UpperCamelCase		:      List[Any] )  ->str:



			'''simple docstring'''







			lowerCamelCase__ :      Union[str, Any]								=		full_name.split("""conv_layers.""" )[-1]
			lowerCamelCase__ :      Union[str, Any]								=		name.split(""".""" )
			lowerCamelCase__ :      Union[str, Any]								=		int(items[0] )
			lowerCamelCase__ :      List[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."
									)
									lowerCamelCase__ :      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."
									)
									lowerCamelCase__ :      List[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."
									)
									lowerCamelCase__ :      str								=		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__ :      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(UpperCamelCase )






def      _A				(UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      Tuple      ,			UpperCamelCase		:      Tuple )  ->List[str]:



			'''simple docstring'''







			lowerCamelCase__ :      Any								=		full_name.split("""adaptor.""" )[-1]
			lowerCamelCase__ :      Optional[Any]								=		name.split(""".""" )

			if items[1].isdigit():
						lowerCamelCase__ :      Tuple								=		int(items[1] )
			else:
						lowerCamelCase__ :      Tuple								=		None

			if "adaptor" not in full_name:
						if "proj_ln" in full_name:
									# has to be layer norm
									if "bias" in name:
												assert (
												    value.shape == adapter.proj_layer_norm.bias.data.shape
												), f"{full_name} has size {value.shape}, but {adapter.proj_layer_norm.bias.data.shape} was found."
												lowerCamelCase__ :      List[str]								=		value
												logger.info(f"Adapter proj layer norm bias was initialized from {full_name}." )
									if "weight" in name:
												assert (
												    value.shape == adapter.proj_layer_norm.weight.data.shape
												), f"{full_name} has size {value.shape}, but {adapter.proj_layer_norm.weight.data.shape} was found."
												lowerCamelCase__ :      Dict								=		value
						else:
									# has to be projection layer
									if "bias" in name:
												assert (
												    value.shape == adapter.proj.bias.data.shape
												), f"{full_name} has size {value.shape}, but {adapter.proj.bias.data.shape} was found."
												lowerCamelCase__ :      List[Any]								=		value
												logger.info(f"Adapter proj layer bias was initialized from {full_name}." )
									if "weight" in name:
												assert (
												    value.shape == adapter.proj.weight.data.shape
												), f"{full_name} has size {value.shape}, but {adapter.proj.weight.data.shape} was found."
												lowerCamelCase__ :      Dict								=		value
												logger.info(f"Adapter proj layer weight was initialized from {full_name}." )
			elif isinstance(UpperCamelCase      ,			UpperCamelCase ):
						if "bias" in name:
									assert (
									    value.shape == adapter.layers[layer_id].conv.bias.data.shape
									), f"{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.bias.data.shape} was found."
									lowerCamelCase__ :      List[str]								=		value
									logger.info(f"Adapter layer {layer_id} bias was initialized from {full_name}." )
						elif "weight" in name:
									assert (
									    value.shape == adapter.layers[layer_id].conv.weight.data.shape
									), f"{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.weight.data.shape} was found."
									lowerCamelCase__ :      Tuple								=		value
									logger.info(f"Adapter layer {layer_id} bias was initialized from {full_name}." )
			else:
						unused_weights.append(UpperCamelCase )






def      _A				(UpperCamelCase		:      Union[str, Any] )  ->Optional[Any]:



			'''simple docstring'''







			lowerCamelCase__ :      Any								=		emb.weight.shape
			lowerCamelCase__ :      Any								=		nn.Linear(UpperCamelCase      ,			UpperCamelCase      ,			bias=UpperCamelCase )
			lowerCamelCase__ :      Any								=		emb.weight.data
			return lin_layer






@torch.no_grad()
def      _A				(UpperCamelCase		:      List[Any]      ,			UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      int      ,			UpperCamelCase		:      List[Any]      ,			UpperCamelCase		:      Dict      ,			UpperCamelCase		:      int      ,			UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      List[Any]      ,			UpperCamelCase		:      Optional[Any]      ,			UpperCamelCase		:      Tuple      ,			UpperCamelCase		:      int      ,			)  ->str:



			'''simple docstring'''







			lowerCamelCase__ :      Tuple								=		WavaVecaConfig.from_pretrained(
			    UpperCamelCase      ,			add_adapter=UpperCamelCase      ,			adapter_stride=UpperCamelCase      ,			adapter_kernel_size=UpperCamelCase      ,			use_auth_token=UpperCamelCase      ,			output_hidden_size=UpperCamelCase      ,			)
			lowerCamelCase__ :      int								=		MBartConfig.from_pretrained(UpperCamelCase )

			# load model
			lowerCamelCase__ :      Optional[int]								=		fairseq.checkpoint_utils.load_model_ensemble_and_task(
			    [checkpoint_path]      ,			arg_overrides={
			        """config_yaml""": config_yaml_path,
			        """data""": """/""".join(dict_path.split("""/""" )[:-1] ),
			        """w2v_path""": checkpoint_path,
			        """load_pretrained_decoder_from""": None,
			    }      ,			)
			lowerCamelCase__ :      Optional[Any]								=		model[0].eval()

			# load feature extractor
			lowerCamelCase__ :      int								=		WavaVecaFeatureExtractor.from_pretrained(UpperCamelCase      ,			use_auth_token=UpperCamelCase )

			# set weights for wav2vec2 encoder
			lowerCamelCase__ :      str								=		WavaVecaModel(UpperCamelCase )

			recursively_load_weights_wavaveca(model.encoder      ,			UpperCamelCase )

			# load decoder weights
			lowerCamelCase__ :      List[str]								=		MBartForCausalLM(UpperCamelCase )
			lowerCamelCase__ :      Dict								=		hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict()      ,			strict=UpperCamelCase )
			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}" )

			lowerCamelCase__ :      Optional[Any]								=		SpeechEncoderDecoderModel(encoder=UpperCamelCase      ,			decoder=UpperCamelCase )
			lowerCamelCase__ :      Optional[Any]								=		False

			lowerCamelCase__ :      Optional[int]								=		MBartaaTokenizer(UpperCamelCase )
			tokenizer.save_pretrained(UpperCamelCase )

			lowerCamelCase__ :      Optional[int]								=		hf_wavavec.config.to_dict()
			lowerCamelCase__ :      Dict								=		tokenizer.pad_token_id
			lowerCamelCase__ :      Union[str, Any]								=		tokenizer.bos_token_id
			lowerCamelCase__ :      Any								=		tokenizer.eos_token_id
			lowerCamelCase__ :      List[str]								=		"""mbart50"""
			lowerCamelCase__ :      Optional[Any]								=		"""wav2vec2"""

			lowerCamelCase__ :      Optional[int]								=		tokenizer.eos_token_id
			lowerCamelCase__ :      int								=		250004
			lowerCamelCase__ :      List[str]								=		tokenizer.eos_token_id

			lowerCamelCase__ :      Dict								=		SpeechEncoderDecoderConfig.from_dict(UpperCamelCase )

			hf_wavavec.save_pretrained(UpperCamelCase )
			feature_extractor.save_pretrained(UpperCamelCase )


if __name__ == "__main__":
				_lowercase     							=						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('''--config_yaml_path''', default=None, type=str, help='''Path to yaml file of fine-tuned model''')
				parser.add_argument(
				    '''--encoder_config_path''',
				    default='''facebook/wav2vec2-xls-r-1b''',
				    type=str,
				    help='''Path to hf encoder wav2vec2 checkpoint config''',
				)
				parser.add_argument(
				    '''--decoder_config_path''',
				    default='''facebook/mbart-large-50-one-to-many-mmt''',
				    type=str,
				    help='''Path to hf decoder checkpoint config''',
				)
				parser.add_argument('''--add_adapter''', default=True, type=bool, help='''whethere to add model adapter layers''')
				parser.add_argument('''--adapter_stride''', default=2, type=int, help='''stride of adapter layers''')
				parser.add_argument('''--adapter_kernel_size''', default=3, type=int, help='''kernel size of adapter layers''')
				parser.add_argument('''--encoder_output_dim''', default=10_24, type=int, help='''encoder output dim''')
				parser.add_argument('''--start_token_id''', default=25_00_04, type=int, help='''`decoder_start_token_id` of model config''')

				_lowercase     							=						parser.parse_args()
				convert_wavaveca_checkpoint(
				    args.checkpoint_path,
				    args.pytorch_dump_folder_path,
				    args.dict_path,
				    args.config_yaml_path,
				    encoder_config_path=args.encoder_config_path,
				    decoder_config_path=args.decoder_config_path,
				    add_adapter=args.add_adapter,
				    adapter_kernel_size=args.adapter_kernel_size,
				    adapter_stride=args.adapter_stride,
				    decoder_start_token_id=args.start_token_id,
				    encoder_output_dim=args.encoder_output_dim,
				)








import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


_lowercase     							=						version.parse(importlib_metadata.version('''nltk'''))
if NLTK_VERSION >= version.Version('''3.6.4'''):
				from nltk import word_tokenize


_lowercase     							=						'''\
@inproceedings{banarjee2005,
  title     = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},
  author    = {Banerjee, Satanjeev  and Lavie, Alon},
  booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},
  month     = jun,
  year      = {2005},
  address   = {Ann Arbor, Michigan},
  publisher = {Association for Computational Linguistics},
  url       = {https://www.aclweb.org/anthology/W05-0909},
  pages     = {65--72},
}
'''

_lowercase     							=						'''\
METEOR, an automatic metric for machine translation evaluation
that is based on a generalized concept of unigram matching between the
machine-produced translation and human-produced reference translations.
Unigrams can be matched based on their surface forms, stemmed forms,
and meanings; furthermore, METEOR can be easily extended to include more
advanced matching strategies. Once all generalized unigram matches
between the two strings have been found, METEOR computes a score for
this matching using a combination of unigram-precision, unigram-recall, and
a measure of fragmentation that is designed to directly capture how
well-ordered the matched words in the machine translation are in relation
to the reference.

METEOR gets an R correlation value of 0.347 with human evaluation on the Arabic
data and 0.331 on the Chinese data. This is shown to be an improvement on
using simply unigram-precision, unigram-recall and their harmonic F1
combination.
'''

_lowercase     							=						'''
Computes METEOR score of translated segments against one or more references.
Args:
    predictions: list of predictions to score. Each prediction
        should be a string with tokens separated by spaces.
    references: list of reference for each prediction. Each
        reference should be a string with tokens separated by spaces.
    alpha: Parameter for controlling relative weights of precision and recall. default: 0.9
    beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3
    gamma: Relative weight assigned to fragmentation penalty. default: 0.5
Returns:
    \'meteor\': meteor score.
Examples:

    >>> meteor = datasets.load_metric(\'meteor\')
    >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"]
    >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"]
    >>> results = meteor.compute(predictions=predictions, references=references)
    >>> print(round(results["meteor"], 4))
    0.6944
'''
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION					, _KWARGS_DESCRIPTION      )
class 				__A					( datasets.Metric      ):





			def        _snake_case    (self				):
						return datasets.MetricInfo(
						    description=_DESCRIPTION							,    citation=_CITATION							,    inputs_description=_KWARGS_DESCRIPTION							,    features=datasets.Features(
						        {
						            """predictions""": datasets.Value("""string"""							,    id="""sequence"""				),
						            """references""": datasets.Value("""string"""							,    id="""sequence"""				),
						        }				)							,    codebase_urls=["""https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py"""]							,    reference_urls=[
						        """https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score""",
						        """https://en.wikipedia.org/wiki/METEOR""",
						    ]							,    )





			def        _snake_case    (self							,    __magic_name__				):
						import nltk

						nltk.download("""wordnet"""				)
						if NLTK_VERSION >= version.Version("""3.6.5"""				):
									nltk.download("""punkt"""				)
						if NLTK_VERSION >= version.Version("""3.6.6"""				):
									nltk.download("""omw-1.4"""				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__=0.9							,    __magic_name__=3							,    __magic_name__=0.5				):
						if NLTK_VERSION >= version.Version("""3.6.5"""				):
									lowerCamelCase__ :      List[str]								=		[
									    meteor_score.single_meteor_score(
									        word_tokenize(__magic_name__				)							,    word_tokenize(__magic_name__				)							,    alpha=__magic_name__							,    beta=__magic_name__							,    gamma=__magic_name__				)
									    for ref, pred in zip(__magic_name__							,    __magic_name__				)
									]
						else:
									lowerCamelCase__ :      int								=		[
									    meteor_score.single_meteor_score(__magic_name__							,    __magic_name__							,    alpha=__magic_name__							,    beta=__magic_name__							,    gamma=__magic_name__				)
									    for ref, pred in zip(__magic_name__							,    __magic_name__				)
									]

						return {"meteor": np.mean(__magic_name__				)}



