






import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

from transformers import (
    WavaVecaConformerConfig,
    WavaVecaConformerForCTC,
    WavaVecaConformerForPreTraining,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
    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.linear_k': 'encoder.layers.*.self_attn.linear_k',
    'self_attn.linear_v': 'encoder.layers.*.self_attn.linear_v',
    'self_attn.linear_q': 'encoder.layers.*.self_attn.linear_q',
    'self_attn.pos_bias_u': 'encoder.layers.*.self_attn.pos_bias_u',
    'self_attn.pos_bias_v': 'encoder.layers.*.self_attn.pos_bias_v',
    'self_attn.linear_out': 'encoder.layers.*.self_attn.linear_out',
    'self_attn.linear_pos': 'encoder.layers.*.self_attn.linear_pos',
    'self_attn.rotary_emb': 'encoder.embed_positions',
    'self_attn_layer_norm': 'encoder.layers.*.self_attn_layer_norm',
    'conv_module.pointwise_conv1': 'encoder.layers.*.conv_module.pointwise_conv1',
    'conv_module.pointwise_conv2': 'encoder.layers.*.conv_module.pointwise_conv2',
    'conv_module.depthwise_conv': 'encoder.layers.*.conv_module.depthwise_conv',
    'conv_module.batch_norm': 'encoder.layers.*.conv_module.batch_norm',
    'conv_module.layer_norm': 'encoder.layers.*.conv_module.layer_norm',
    'ffn1.w_1': 'encoder.layers.*.ffn1.intermediate_dense',
    'ffn1.w_2': 'encoder.layers.*.ffn1.output_dense',
    'ffn1.layer_norm': 'encoder.layers.*.ffn1_layer_norm',
    'ffn2.w_1': 'encoder.layers.*.ffn2.intermediate_dense',
    'ffn2.w_2': 'encoder.layers.*.ffn2.output_dense',
    'ffn2.layer_norm': 'encoder.layers.*.ffn2_layer_norm',
    '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',
}
__lowerCAmelCase       		=      [
    'lm_head',
    'quantizer.weight_proj',
    'quantizer.codevectors',
    'project_q',
    'project_hid',
]





def 		_UpperCAmelCase   (							__A							:   Optional[int]						,		__A							:   str						,		__A							:   Dict						,		__A							:   List[Any]						,		__A							:   List[Any]      ):
				for attribute in key.split('''.'''      ):
								a_		:  int											=      getattr(__A						,		__A      )

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

				if hf_shape != value.shape:
								raise ValueError(
								    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_		:  Optional[int]											=      value
				elif weight_type == "weight_g":
								a_		:  List[Any]											=      value
				elif weight_type == "weight_v":
								a_		:  Any											=      value
				elif weight_type == "bias":
								a_		:  List[Any]											=      value
				elif weight_type == "running_mean":
								a_		:  str											=      value
				elif weight_type == "running_var":
								a_		:  List[str]											=      value
				elif weight_type == "num_batches_tracked":
								a_		:  Optional[Any]											=      value
				elif weight_type == "inv_freq":
								a_		:  Union[str, Any]											=      value
				else:
								a_		:  Tuple											=      value

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





def 		_UpperCAmelCase   (							__A							:   str						,		__A							:   Union[str, Any]						,		__A							:   int      ):
				a_		:  List[str]											=      []
				a_		:  List[str]											=      fairseq_model.state_dict()

				a_		:  Union[str, Any]											=      hf_model.wavaveca_conformer.feature_extractor

				for name, value in fairseq_dict.items():
								a_		:  Optional[int]											=      False
								if "conv_layers" in name:
												load_conv_layer(
												    __A						,		__A						,		__A						,		__A						,		hf_model.config.feat_extract_norm == '''group'''						,		)
												a_		:  Optional[Any]											=      True
								else:
												for key, mapped_key in MAPPING.items():
																a_		:  Union[str, Any]											=      '''wav2vec2_conformer.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
																if key in name or key.split('''w2v_model.'''      )[-1] == name.split('''.'''      )[0]:
																				a_		:  Tuple											=      True
																				if "*" in mapped_key:
																								a_		:  Any											=      name.split(__A      )[0].split('''.'''      )[-2]
																								a_		:  Tuple											=      mapped_key.replace('''*'''						,		__A      )
																				if "pos_bias_u" in name:
																								a_		:  List[Any]											=      None
																				elif "pos_bias_v" in name:
																								a_		:  List[Any]											=      None
																				elif "weight_g" in name:
																								a_		:  str											=      '''weight_g'''
																				elif "weight_v" in name:
																								a_		:  List[Any]											=      '''weight_v'''
																				elif "bias" in name:
																								a_		:  List[str]											=      '''bias'''
																				elif "weight" in name:
																								# TODO: don't match quantizer.weight_proj
																								a_		:  List[Any]											=      '''weight'''
																				elif "running_mean" in name:
																								a_		:  Any											=      '''running_mean'''
																				elif "inv_freq" in name:
																								a_		:  List[str]											=      '''inv_freq'''
																				elif "running_var" in name:
																								a_		:  Optional[int]											=      '''running_var'''
																				elif "num_batches_tracked" in name:
																								a_		:  Optional[Any]											=      '''num_batches_tracked'''
																				else:
																								a_		:  Dict											=      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 		_UpperCAmelCase   (							__A							:   str						,		__A							:   int						,		__A							:   int						,		__A							:   List[str]						,		__A							:   int      ):
				a_		:  Optional[int]											=      full_name.split('''conv_layers.'''      )[-1]
				a_		:  Optional[Any]											=      name.split('''.'''      )
				a_		:  List[str]											=      int(items[0]      )
				a_		:  Tuple											=      int(items[1]      )

				if type_id == 0:
								if "bias" in name:
												if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
																raise ValueError(
																    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:
												if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
																raise ValueError(
																    f'{full_name} has size {value.shape}, but'
																    f' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'      )
												a_		:  int											=      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:
												if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
																raise ValueError(
																    f'{full_name} has size {value.shape}, but'
																    f' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.'      )
												a_		:  List[str]											=      value
												logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'      )
								elif "weight" in name:
												if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
																raise ValueError(
																    f'{full_name} has size {value.shape}, but'
																    f' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.'      )
												a_		:  Any											=      value
												logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'      )
				else:
								unused_weights.append(__A      )





@torch.no_grad()
def 		_UpperCAmelCase   (							__A							:   str						,		__A							:   int						,		__A							:   Dict=None						,		__A							:   Tuple=None						,		__A							:   int=True      ):
				if config_path is not None:
								a_		:  Dict											=      WavaVecaConformerConfig.from_pretrained(__A						,		hidden_act='''swish'''      )
				else:
								a_		:  List[Any]											=      WavaVecaConformerConfig()

				if "rope" in checkpoint_path:
								a_		:  Union[str, Any]											=      '''rotary'''

				if is_finetuned:
								if dict_path:
												a_		:  Tuple											=      Dictionary.load(__A      )

												# important change bos & pad token id since CTC symbol is <pad> and
												# not <s> as in fairseq
												a_		:  Dict											=      target_dict.pad_index
												a_		:  Union[str, Any]											=      target_dict.bos_index
												a_		:  Dict											=      target_dict.eos_index
												a_		:  Union[str, Any]											=      len(target_dict.symbols      )
												a_		:  str											=      os.path.join(__A						,		'''vocab.json'''      )
												if not os.path.isdir(__A      ):
																logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(__A      )      )
																return
												os.makedirs(__A						,		exist_ok=__A      )
												a_		:  Dict											=      target_dict.indices

												# fairseq has the <pad> and <s> switched
												a_		:  Union[str, Any]											=      0
												a_		:  Dict											=      1
												with open(__A						,		'''w'''						,		encoding='''utf-8'''      ) as vocab_handle:
																json.dump(__A						,		__A      )
												a_		:  Any											=      WavaVecaCTCTokenizer(
												    __A						,		unk_token=target_dict.unk_word						,		pad_token=target_dict.pad_word						,		bos_token=target_dict.bos_word						,		eos_token=target_dict.eos_word						,		word_delimiter_token='''|'''						,		do_lower_case=__A						,		)
												a_		:  Optional[Any]											=      True if config.feat_extract_norm == '''layer''' else False
												a_		:  List[Any]											=      WavaVecaFeatureExtractor(
												    feature_size=1						,		sampling_rate=1_60_00						,		padding_value=0						,		do_normalize=__A						,		return_attention_mask=__A						,		)
												a_		:  Dict											=      WavaVecaProcessor(feature_extractor=__A						,		tokenizer=__A      )
												processor.save_pretrained(__A      )

								a_		:  Dict											=      WavaVecaConformerForCTC(__A      )
				else:
								a_		:  Any											=      WavaVecaConformerForPreTraining(__A      )

				if is_finetuned:
								a_		:  Any											=      fairseq.checkpoint_utils.load_model_ensemble_and_task(
								    [checkpoint_path]						,		arg_overrides={'''data''': '''/'''.join(dict_path.split('''/'''      )[:-1]      )}      )
				else:
								a_		:  str											=      argparse.Namespace(task='''audio_pretraining'''      )
								a_		:  str											=      fairseq.tasks.setup_task(__A      )

								a_		:  Union[str, Any]											=      fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]						,		task=__A      )

				a_		:  Optional[int]											=      model[0].eval()

				recursively_load_weights(__A						,		__A						,		not is_finetuned      )

				hf_wavavec.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('--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_path', default=None, type=str, help='Path to hf config.json of model to convert')
		parser.add_argument(
		    '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not'
		)
		__lowerCAmelCase       		=      parser.parse_args()
		convert_wavaveca_conformer_checkpoint(
		    args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
		)












'''simple docstring'''







import re
import string

import numpy as np

import datasets


__lowerCAmelCase       		=      '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n'

__lowerCAmelCase       		=      '\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results["exact_match"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n    >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    33.3\n\n'

__lowerCAmelCase       		=      '\n'





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,   _KWARGS_DESCRIPTION       )
class 	SCREAMING_SNAKE_CASE					(					datasets.Metric       ):






			def 			SCREAMING_SNAKE_CASE      ( self      :			Optional[Any]					)			->			int:
							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'''					),
							        }					)  ,						reference_urls=[]  ,						)







			def 			SCREAMING_SNAKE_CASE      ( self      :			str  ,						__SCREAMING_SNAKE_CASE      :			List[Any]  ,						__SCREAMING_SNAKE_CASE      :			Optional[int]  ,						__SCREAMING_SNAKE_CASE      :			Dict=None  ,						__SCREAMING_SNAKE_CASE      :			int=False  ,						__SCREAMING_SNAKE_CASE      :			Optional[int]=False  ,						__SCREAMING_SNAKE_CASE      :			Dict=False  ,						)			->			str:
							if regexes_to_ignore is not None:
											for s in regexes_to_ignore:
															a_		:  Optional[Any]											=      np.array([re.sub(__SCREAMING_SNAKE_CASE  ,						''''''  ,						__SCREAMING_SNAKE_CASE					) for x in predictions]					)
															a_		:  int											=      np.array([re.sub(__SCREAMING_SNAKE_CASE  ,						''''''  ,						__SCREAMING_SNAKE_CASE					) for x in references]					)
							else:
											a_		:  List[str]											=      np.asarray(__SCREAMING_SNAKE_CASE					)
											a_		:  Any											=      np.asarray(__SCREAMING_SNAKE_CASE					)

							if ignore_case:
											a_		:  List[str]											=      np.char.lower(__SCREAMING_SNAKE_CASE					)
											a_		:  List[Any]											=      np.char.lower(__SCREAMING_SNAKE_CASE					)

							if ignore_punctuation:
											a_		:  Any											=      string.punctuation.maketrans(''''''  ,						''''''  ,						string.punctuation					)
											a_		:  Union[str, Any]											=      np.char.translate(__SCREAMING_SNAKE_CASE  ,						table=__SCREAMING_SNAKE_CASE					)
											a_		:  int											=      np.char.translate(__SCREAMING_SNAKE_CASE  ,						table=__SCREAMING_SNAKE_CASE					)

							if ignore_numbers:
											a_		:  int											=      string.digits.maketrans(''''''  ,						''''''  ,						string.digits					)
											a_		:  Optional[int]											=      np.char.translate(__SCREAMING_SNAKE_CASE  ,						table=__SCREAMING_SNAKE_CASE					)
											a_		:  Dict											=      np.char.translate(__SCREAMING_SNAKE_CASE  ,						table=__SCREAMING_SNAKE_CASE					)

							a_		:  Optional[Any]											=      predictions == references

							return {"exact_match": np.mean(__SCREAMING_SNAKE_CASE					) * 100}




