

'''simple docstring'''





import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.testing_utils import require_tensorflow_text, require_tf, slow


if is_tf_available():
							import tensorflow as tf

if is_tensorflow_text_available():
							from transformers.models.bert import TFBertTokenizer


UpperCamelCase_    						=       ["""bert-base-uncased""", """bert-base-cased"""]
UpperCamelCase_    						=       """hf-internal-testing/tiny-bert-tf-only"""

if is_tf_available():





							class 		__SCREAMING_SNAKE_CASE							(			tf.keras.Model      ):







											def __init__(       self     :		Union[str, Any]		,					UpperCAmelCase__     :		List[Any]   ):
																	'''simple docstring'''
																	super().__init__()
																	lowercase :							Dict    		=tokenizer
																	lowercase :							str    		=AutoConfig.from_pretrained(UpperCAmelCase__   )
																	lowercase :							str    		=TFAutoModel.from_config(UpperCAmelCase__   )







											def  lowerCamelCase_	(       self     :		Any		,					UpperCAmelCase__     :		List[Any]   ):
																	'''simple docstring'''
																	lowercase :							List[Any]    		=self.tokenizer(UpperCAmelCase__   )
																	lowercase :							int    		=self.bert(**UpperCAmelCase__   )
																	return out["pooler_output"]





@require_tf
@require_tensorflow_text
class 		__SCREAMING_SNAKE_CASE							(			unittest.TestCase      ):







				def  lowerCamelCase_	(       self     :		int   ):
										'''simple docstring'''
										super().setUp()

										lowercase :							str    		=[
										    BertTokenizer.from_pretrained(UpperCAmelCase__   ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2)
										]  # repeat for when fast_bert_tokenizer=false
										lowercase :							Tuple    		=[TFBertTokenizer.from_pretrained(UpperCAmelCase__   ) for checkpoint in TOKENIZER_CHECKPOINTS] + [
										    TFBertTokenizer.from_pretrained(UpperCAmelCase__		,					use_fast_bert_tokenizer=UpperCAmelCase__   )
										    for checkpoint in TOKENIZER_CHECKPOINTS
										]
										assert len(self.tokenizers   ) == len(self.tf_tokenizers   )

										lowercase :							Any    		=[
										    '''This is a straightforward English test sentence.''',
										    '''This one has some weird characters\rto\nsee\r\nif  those\u00E9break things.''',
										    '''Now we\'re going to add some Chinese: 一 二 三 一二三''',
										    '''And some much more rare Chinese: 齉 堃 齉堃''',
										    '''Je vais aussi écrire en français pour tester les accents''',
										    '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''',
										]
										lowercase :							Optional[Any]    		=list(zip(self.test_sentences		,					self.test_sentences[::-1]   )   )







				def  lowerCamelCase_	(       self     :		str   ):
										'''simple docstring'''
										for tokenizer, tf_tokenizer in zip(self.tokenizers		,					self.tf_tokenizers   ):
																for test_inputs in (self.test_sentences, self.paired_sentences):
																						lowercase :							Tuple    		=tokenizer(UpperCAmelCase__		,					return_tensors='''tf'''		,					padding='''longest'''   )
																						lowercase :							Optional[int]    		=tf_tokenizer(UpperCAmelCase__   )

																						for key in python_outputs.keys():
																												self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape   )   )
																												self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key]		,					tf.intaa   ) == tf_outputs[key]   )   )







				@slow
				def  lowerCamelCase_	(       self     :		Dict   ):
										'''simple docstring'''
										for tf_tokenizer in self.tf_tokenizers:
																lowercase :							int    		=tf_tokenizer(self.paired_sentences   )
																lowercase :							Dict    		=tf_tokenizer(
																    text=[sentence[0] for sentence in self.paired_sentences]		,					text_pair=[sentence[1] for sentence in self.paired_sentences]		,					)
																for key in merged_outputs.keys():
																						self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key]		,					tf.intaa   ) == separated_outputs[key]   )   )







				@slow
				def  lowerCamelCase_	(       self     :		List[Any]   ):
										'''simple docstring'''
										for tf_tokenizer in self.tf_tokenizers:
																lowercase :							Any    		=tf.function(UpperCAmelCase__   )
																for test_inputs in (self.test_sentences, self.paired_sentences):
																						lowercase :							int    		=tf.constant(UpperCAmelCase__   )
																						lowercase :							List[str]    		=compiled_tokenizer(UpperCAmelCase__   )
																						lowercase :							Tuple    		=tf_tokenizer(UpperCAmelCase__   )

																						for key in eager_outputs.keys():
																												self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]   )   )







				@slow
				def  lowerCamelCase_	(       self     :		List[Any]   ):
										'''simple docstring'''
										for tf_tokenizer in self.tf_tokenizers:
																lowercase :							str    		=ModelToSave(tokenizer=UpperCAmelCase__   )
																lowercase :							List[str]    		=tf.convert_to_tensor(self.test_sentences   )
																lowercase :							List[Any]    		=model(UpperCAmelCase__   )  # Build model with some sample inputs
																with TemporaryDirectory() as tempdir:
																						lowercase :							List[str]    		=Path(UpperCAmelCase__   ) / '''saved.model'''
																						model.save(UpperCAmelCase__   )
																						lowercase :							Dict    		=tf.keras.models.load_model(UpperCAmelCase__   )
																lowercase :							Dict    		=loaded_model(UpperCAmelCase__   )
																# We may see small differences because the loaded model is compiled, so we need an epsilon for the test
																self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output   )   )		,					1E-5   )








'''simple docstring'''





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

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






def 				_lowerCAmelCase			(   __magic_name__						:     Any   , __magic_name__						:     Union[str, Any]   , __magic_name__						:     Union[str, Any]   , __magic_name__						:     Union[str, Any]   , __magic_name__						:     Tuple						)				->  str:
						for attribute in key.split('''.'''						):
												lowercase :							Tuple    		=getattr(__magic_name__   , __magic_name__						)

						if weight_type is not None:
												lowercase :							Optional[int]    		=getattr(__magic_name__   , __magic_name__						).shape
						else:
												lowercase :							List[Any]    		=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":
												lowercase :							Any    		=value
						elif weight_type == "weight_g":
												lowercase :							List[Any]    		=value
						elif weight_type == "weight_v":
												lowercase :							Union[str, Any]    		=value
						elif weight_type == "bias":
												lowercase :							Tuple    		=value
						elif weight_type == "running_mean":
												lowercase :							Union[str, Any]    		=value
						elif weight_type == "running_var":
												lowercase :							str    		=value
						elif weight_type == "num_batches_tracked":
												lowercase :							Tuple    		=value
						elif weight_type == "inv_freq":
												lowercase :							Optional[Any]    		=value
						else:
												lowercase :							Tuple    		=value

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






def 				_lowerCAmelCase			(   __magic_name__						:     List[Any]   , __magic_name__						:     Union[str, Any]   , __magic_name__						:     str						)				->  Union[str, Any]:
						lowercase :							Optional[int]    		=[]
						lowercase :							Tuple    		=fairseq_model.state_dict()

						lowercase :							List[Any]    		=hf_model.wavaveca_conformer.feature_extractor

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

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






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






@torch.no_grad()
def 				_lowerCAmelCase			(   __magic_name__						:     List[str]   , __magic_name__						:     Optional[Any]   , __magic_name__						:     Tuple=None   , __magic_name__						:     Optional[Any]=None   , __magic_name__						:     Union[str, Any]=True						)				->  Union[str, Any]:
						if config_path is not None:
												lowercase :							Optional[Any]    		=WavaVecaConformerConfig.from_pretrained(__magic_name__   , hidden_act='''swish'''						)
						else:
												lowercase :							Optional[int]    		=WavaVecaConformerConfig()

						if "rope" in checkpoint_path:
												lowercase :							Dict    		='''rotary'''

						if is_finetuned:
												if dict_path:
																		lowercase :							Optional[Any]    		=Dictionary.load(__magic_name__						)

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

																		# fairseq has the <pad> and <s> switched
																		lowercase :							str    		=0
																		lowercase :							List[Any]    		=1
																		with open(__magic_name__   , '''w'''   , encoding='''utf-8'''						) as vocab_handle:
																								json.dump(__magic_name__   , __magic_name__						)
																		lowercase :							List[str]    		=WavaVecaCTCTokenizer(
																		    __magic_name__   , 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=__magic_name__   , )
																		lowercase :							Optional[int]    		=True if config.feat_extract_norm == '''layer''' else False
																		lowercase :							str    		=WavaVecaFeatureExtractor(
																		    feature_size=1   , sampling_rate=16000   , padding_value=0   , do_normalize=__magic_name__   , return_attention_mask=__magic_name__   , )
																		lowercase :							Tuple    		=WavaVecaProcessor(feature_extractor=__magic_name__   , tokenizer=__magic_name__						)
																		processor.save_pretrained(__magic_name__						)

												lowercase :							str    		=WavaVecaConformerForCTC(__magic_name__						)
						else:
												lowercase :							Tuple    		=WavaVecaConformerForPreTraining(__magic_name__						)

						if is_finetuned:
												lowercase		,	lowercase		,	lowercase :							Optional[int]    		=fairseq.checkpoint_utils.load_model_ensemble_and_task(
												    [checkpoint_path]   , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/'''						)[:-1]						)}						)
						else:
												lowercase :							Dict    		=argparse.Namespace(task='''audio_pretraining'''						)
												lowercase :							Optional[int]    		=fairseq.tasks.setup_task(__magic_name__						)

												lowercase		,	lowercase		,	lowercase :							str    		=fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]   , task=__magic_name__						)

						lowercase :							List[Any]    		=model[0].eval()

						recursively_load_weights(__magic_name__   , __magic_name__   , not is_finetuned						)

						hf_wavavec.save_pretrained(__magic_name__						)


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("""--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"""
							)
							UpperCamelCase_    						=       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
							)





