



'''simple docstring'''



import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

from transformers import (
    UniSpeechConfig,
    UniSpeechForCTC,
    UniSpeechForPreTraining,
    WavaVecaFeatureExtractor,
    WavaVecaPhonemeCTCTokenizer,
    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.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''': '''ctc_proj''',
    '''mask_emb''': '''masked_spec_embed''',
}
lowerCamelCase									=							[
    '''ctc_proj''',
    '''quantizer.weight_proj''',
    '''quantizer.codevectors''',
    '''project_q''',
    '''project_hid''',
]



def 	_A							( _lowerCAmelCase	, _lowerCAmelCase	, _lowerCAmelCase	, _lowerCAmelCase	, _lowerCAmelCase	, _lowerCAmelCase       ):



							"""simple docstring"""



							for attribute in key.split('.'       ):
														if is_finetuned:
																					if attribute in ["quantizer", "project_q", "project_hid"]:
																												# those layers are only relevant for pretraining and should be dropped
																												return

																					if attribute == "ctc_proj":
																												# we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models
																												__lowercase													='''lm_head'''

														__lowercase													=getattr(UpperCAmelCase_	, UpperCAmelCase_       )

							if weight_type is not None:
														__lowercase													=getattr(UpperCAmelCase_	, UpperCAmelCase_       ).shape
							else:
														__lowercase													=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":
														__lowercase													=value
							elif weight_type == "weight_g":
														__lowercase													=value
							elif weight_type == "weight_v":
														__lowercase													=value
							elif weight_type == "bias":
														__lowercase													=value
							else:
														__lowercase													=value

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



def 	_A							( _lowerCAmelCase	, _lowerCAmelCase	, _lowerCAmelCase       ):



							"""simple docstring"""



							__lowercase													=[]
							__lowercase													=fairseq_model.state_dict()

							__lowercase													=hf_model.unispeech.feature_extractor

							for name, value in fairseq_dict.items():
														__lowercase													=False
														if "conv_layers" in name:
																					load_conv_layer(
																					    UpperCAmelCase_	, UpperCAmelCase_	, UpperCAmelCase_	, UpperCAmelCase_	, hf_model.config.feat_extract_norm == 'group'	, )
																					__lowercase													=True
														else:
																					for key, mapped_key in MAPPING.items():
																												__lowercase													='''unispeech.''' + 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]:
																																			__lowercase													=True
																																			if "*" in mapped_key:
																																										__lowercase													=name.split(UpperCAmelCase_       )[0].split('.'       )[-2]
																																										__lowercase													=mapped_key.replace('*'	, UpperCAmelCase_       )
																																			if "weight_g" in name:
																																										__lowercase													='''weight_g'''
																																			elif "weight_v" in name:
																																										__lowercase													='''weight_v'''
																																			elif "bias" in name:
																																										__lowercase													='''bias'''
																																			elif "weight" in name:
																																										# TODO: don't match quantizer.weight_proj
																																										__lowercase													='''weight'''
																																			else:
																																										__lowercase													=None
																																			set_recursively(UpperCAmelCase_	, UpperCAmelCase_	, UpperCAmelCase_	, UpperCAmelCase_	, UpperCAmelCase_	, UpperCAmelCase_       )
																												continue
														if not is_used:
																					unused_weights.append(UpperCAmelCase_       )

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



def 	_A							( _lowerCAmelCase	, _lowerCAmelCase	, _lowerCAmelCase	, _lowerCAmelCase	, _lowerCAmelCase       ):



							"""simple docstring"""



							__lowercase													=full_name.split('conv_layers.'       )[-1]
							__lowercase													=name.split('.'       )
							__lowercase													=int(items[0]       )
							__lowercase													=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."""
																					)
																					__lowercase													=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."""
																					)
																					__lowercase													=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."
																					)
																					__lowercase													=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."""
																					)
																					__lowercase													=value
																					logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."""       )
							else:
														unused_weights.append(UpperCAmelCase_       )



@torch.no_grad()
def 	_A							( _lowerCAmelCase	, _lowerCAmelCase	, _lowerCAmelCase=None	, _lowerCAmelCase=None	, _lowerCAmelCase=True       ):



							"""simple docstring"""



							if config_path is not None:
														__lowercase													=UniSpeechConfig.from_pretrained(UpperCAmelCase_       )
							else:
														__lowercase													=UniSpeechConfig()

							if is_finetuned:
														if dict_path:
																					__lowercase													=Dictionary.load_from_json(UpperCAmelCase_       )

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

																					# fairseq has the <pad> and <s> switched
																					__lowercase													=42
																					__lowercase													=43
																					with open(UpperCAmelCase_	, 'w'	, encoding='utf-8'       ) as vocab_handle:
																												json.dump(UpperCAmelCase_	, UpperCAmelCase_       )
																					__lowercase													=WavaVecaPhonemeCTCTokenizer(
																					    UpperCAmelCase_	, 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=UpperCAmelCase_	, )
																					__lowercase													=True if config.feat_extract_norm == '''layer''' else False
																					__lowercase													=WavaVecaFeatureExtractor(
																					    feature_size=1	, sampling_rate=16_000	, padding_value=0	, do_normalize=UpperCAmelCase_	, return_attention_mask=UpperCAmelCase_	, )
																					__lowercase													=WavaVecaProcessor(feature_extractor=UpperCAmelCase_	, tokenizer=UpperCAmelCase_       )
																					processor.save_pretrained(UpperCAmelCase_       )

														__lowercase													=UniSpeechForCTC(UpperCAmelCase_       )
							else:
														__lowercase													=UniSpeechForPreTraining(UpperCAmelCase_       )

							if is_finetuned:
														__lowercase													=fairseq.checkpoint_utils.load_model_ensemble_and_task(
														    [checkpoint_path]	, arg_overrides={'data': '/'.join(dict_path.split('/'       )[:-1]       ), 'w2v_path': checkpoint_path}       )
							else:
														__lowercase													=fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]       )

							__lowercase													=model[0].eval()

							recursively_load_weights(UpperCAmelCase_	, UpperCAmelCase_	, UpperCAmelCase_       )

							hf_unispeech.save_pretrained(UpperCAmelCase_       )


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_unispeech_checkpoint(
		    args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
		)







import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


snake_case							:       Optional[int]										=	logging.get_logger(__name__)

snake_case							:       Optional[int]										=	{
    '''microsoft/unispeech-large-1500h-cv''': (
        '''https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json'''
    ),
    # See all UniSpeech models at https://huggingface.co/models?filter=unispeech
}







class 						_snake_case    ( _snake_case				):
 SCREAMING_SNAKE_CASE__ =			'unispeech'




 def __init__(						self   ,    _lowerCamelCase=32   ,    _lowerCamelCase=768   ,    _lowerCamelCase=12   ,    _lowerCamelCase=12   ,    _lowerCamelCase=3072   ,    _lowerCamelCase="gelu"   ,    _lowerCamelCase=0.1   ,    _lowerCamelCase=0.1   ,    _lowerCamelCase=0.1   ,    _lowerCamelCase=0.0   ,    _lowerCamelCase=0.0   ,    _lowerCamelCase=0.1   ,    _lowerCamelCase=0.1   ,    _lowerCamelCase=0.02   ,    _lowerCamelCase=1e-5   ,    _lowerCamelCase="group"   ,    _lowerCamelCase="gelu"   ,    _lowerCamelCase=(512, 512, 512, 512, 512, 512, 512)   ,    _lowerCamelCase=(5, 2, 2, 2, 2, 2, 2)   ,    _lowerCamelCase=(10, 3, 3, 3, 3, 2, 2)   ,    _lowerCamelCase=False   ,    _lowerCamelCase=128   ,    _lowerCamelCase=16   ,    _lowerCamelCase=False   ,    _lowerCamelCase=True   ,    _lowerCamelCase=0.05   ,    _lowerCamelCase=10   ,    _lowerCamelCase=2   ,    _lowerCamelCase=0.0   ,    _lowerCamelCase=10   ,    _lowerCamelCase=0   ,    _lowerCamelCase=320   ,    _lowerCamelCase=2   ,    _lowerCamelCase=0.1   ,    _lowerCamelCase=100   ,    _lowerCamelCase=256   ,    _lowerCamelCase=256   ,    _lowerCamelCase=0.1   ,    _lowerCamelCase="mean"   ,    _lowerCamelCase=False   ,    _lowerCamelCase=False   ,    _lowerCamelCase=256   ,    _lowerCamelCase=80   ,    _lowerCamelCase=0   ,    _lowerCamelCase=1   ,    _lowerCamelCase=2   ,    _lowerCamelCase=0.5   ,    **_lowerCamelCase   ,    ):
       super().__init__(**_lowerCamelCase   ,    pad_token_id=_lowerCamelCase   ,    bos_token_id=_lowerCamelCase   ,    eos_token_id=_lowerCamelCase       )
       a		:Any									=			hidden_size
       a		:str									=			feat_extract_norm
       a		:List[Any]									=			feat_extract_activation
       a		:Tuple									=			list(_lowerCamelCase       )
       a		:Any									=			list(_lowerCamelCase       )
       a		:List[Any]									=			list(_lowerCamelCase       )
       a		:Union[str, Any]									=			conv_bias
       a		:str									=			num_conv_pos_embeddings
       a		:str									=			num_conv_pos_embedding_groups
       a		:Tuple									=			len(self.conv_dim       )
       a		:int									=			num_hidden_layers
       a		:Any									=			intermediate_size
       a		:Optional[Any]									=			hidden_act
       a		:Tuple									=			num_attention_heads
       a		:Any									=			hidden_dropout
       a		:Any									=			attention_dropout
       a		:Optional[Any]									=			activation_dropout
       a		:Optional[Any]									=			feat_proj_dropout
       a		:Any									=			final_dropout
       a		:int									=			layerdrop
       a		:int									=			layer_norm_eps
       a		:Dict									=			initializer_range
       a		:Dict									=			num_ctc_classes
       a		:Optional[Any]									=			vocab_size
       a		:str									=			do_stable_layer_norm
       a		:Tuple									=			use_weighted_layer_sum
       a		:Any									=			classifier_proj_size

       if (
           (len(self.conv_stride       ) != self.num_feat_extract_layers)
           or (len(self.conv_kernel       ) != self.num_feat_extract_layers)
           or (len(self.conv_dim       ) != self.num_feat_extract_layers)
       ):
             raise ValueError(
                 '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =='''
                 ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ='''
                 F''' {len(self.conv_dim       )}`, `len(config.conv_stride) = {len(self.conv_stride       )}`,'''
                 F''' `len(config.conv_kernel) = {len(self.conv_kernel       )}`.'''       )

       # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
       a		:List[Any]									=			apply_spec_augment
       a		:Any									=			mask_time_prob
       a		:Union[str, Any]									=			mask_time_length
       a		:str									=			mask_time_min_masks
       a		:Tuple									=			mask_feature_prob
       a		:Dict									=			mask_feature_length
       a		:int									=			mask_feature_min_masks

       # parameters for pretraining with codevector quantized representations
       a		:Union[str, Any]									=			num_codevectors_per_group
       a		:Dict									=			num_codevector_groups
       a		:List[Any]									=			contrastive_logits_temperature
       a		:Union[str, Any]									=			feat_quantizer_dropout
       a		:Optional[Any]									=			num_negatives
       a		:Tuple									=			codevector_dim
       a		:Optional[Any]									=			proj_codevector_dim
       a		:Union[str, Any]									=			diversity_loss_weight

       # ctc loss
       a		:List[Any]									=			ctc_loss_reduction
       a		:Union[str, Any]									=			ctc_zero_infinity

       # pretraining loss
       a		:int									=			replace_prob




 @property
 def 			SCREAMING_SNAKE_CASE__							(						self       ):
       return functools.reduce(operator.mul   ,    self.conv_stride   ,    1       )





