


'''simple docstring'''


import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

# Register SEW's fairseq modules
from sew_asapp import tasks  # noqa: F401

from transformers import (
    SEWConfig,
    SEWForCTC,
    SEWModel,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
    logging,
)


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

_UpperCamelCase 							=  {
    """post_extract_proj""": """feature_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.upsample.0""": """encoder.upsample.projection""",
    """encoder.layer_norm""": """encoder.layer_norm""",
    """w2v_model.layer_norm""": """layer_norm""",
    """w2v_encoder.proj""": """lm_head""",
    """mask_emb""": """masked_spec_embed""",
}


def 		_lowercase (SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE							):




     '''simple docstring'''





     for attribute in key.split("."							):
          __A	:       List[str]      =							getattr(SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE							)

     if weight_type is not None:
          __A	:       int      =							getattr(SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE							).shape
     else:
          __A	:       int      =							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	:       Optional[int]      =							value
     elif weight_type == "weight_g":
          __A	:       Any      =							value
     elif weight_type == "weight_v":
          __A	:       Dict      =							value
     elif weight_type == "bias":
          __A	:       List[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 		_lowercase (SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE							):




     '''simple docstring'''





     __A	:       Optional[Any]      =							[]
     __A	:       Any      =							fairseq_model.state_dict()

     __A	:       Union[str, Any]      =							hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor

     for name, value in fairseq_dict.items():
          __A	:       List[Any]      =							False
          if "conv_layers" in name:
               load_conv_layer(
                   SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					hf_model.config.feat_extract_norm == "group"       ,					)
               __A	:       Union[str, Any]      =							True
          else:
               for key, mapped_key in MAPPING.items():
                    __A	:       Any      =							"sew." + mapped_key if (is_finetuned and mapped_key != "lm_head") else mapped_key

                    if key in name or key.split("w2v_model."							)[-1] == name.split("."							)[0]:
                         __A	:       Tuple      =							True
                         if "*" in mapped_key:
                              __A	:       List[Any]      =							name.split(SCREAMING_SNAKE_CASE							)[0].split("."							)[-2]
                              __A	:       int      =							mapped_key.replace("*"       ,					SCREAMING_SNAKE_CASE							)
                         if "weight_g" in name:
                              __A	:       str      =							"weight_g"
                         elif "weight_v" in name:
                              __A	:       List[str]      =							"weight_v"
                         elif "weight" in name:
                              __A	:       List[Any]      =							"weight"
                         elif "bias" in name:
                              __A	:       List[str]      =							"bias"
                         else:
                              __A	:       Any      =							None
                         set_recursively(SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE							)
                    continue
          if not is_used:
               unused_weights.append(SCREAMING_SNAKE_CASE							)

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


def 		_lowercase (SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE							):




     '''simple docstring'''





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


def 		_lowercase (SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE							):




     '''simple docstring'''





     __A	:       Dict      =							SEWConfig()
     if is_finetuned:
          __A	:       str      =							model.wav_encoder.wav_model.cfg
     else:
          __A	:       Union[str, Any]      =							model.cfg

     __A	:       List[str]      =							fs_config.conv_bias
     __A	:       Optional[Any]      =							eval(fs_config.conv_feature_layers							)
     __A	:       str      =							[x[0] for x in conv_layers]
     __A	:       Optional[int]      =							[x[1] for x in conv_layers]
     __A	:       List[str]      =							[x[2] for x in conv_layers]
     __A	:       Optional[int]      =							"gelu"
     __A	:       Union[str, Any]      =							"layer" if fs_config.extractor_mode == "layer_norm" else "group"
     __A	:       Any      =							0.0
     __A	:       Any      =							fs_config.activation_fn.name
     __A	:       List[str]      =							fs_config.encoder_embed_dim
     __A	:       str      =							0.02
     __A	:       Union[str, Any]      =							fs_config.encoder_ffn_embed_dim
     __A	:       List[str]      =							1E-5
     __A	:       int      =							fs_config.encoder_layerdrop
     __A	:       Any      =							fs_config.encoder_attention_heads
     __A	:       str      =							fs_config.conv_pos_groups
     __A	:       int      =							fs_config.conv_pos
     __A	:       List[Any]      =							len(SCREAMING_SNAKE_CASE							)
     __A	:       str      =							fs_config.encoder_layers
     __A	:       Dict      =							fs_config.squeeze_factor

     # take care of any params that are overridden by the Wav2VecCtc model
     if is_finetuned:
          __A	:       Tuple      =							model.cfg
          __A	:       List[Any]      =							fs_config.final_dropout
          __A	:       Any      =							fs_config.layerdrop
     __A	:       Any      =							fs_config.activation_dropout
     __A	:       Union[str, Any]      =							fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0
     __A	:       Optional[int]      =							fs_config.attention_dropout
     __A	:       Union[str, Any]      =							fs_config.dropout_input
     __A	:       Optional[Any]      =							fs_config.dropout
     __A	:       List[str]      =							fs_config.mask_channel_length
     __A	:       Tuple      =							fs_config.mask_channel_prob
     __A	:       Dict      =							fs_config.mask_length
     __A	:       str      =							fs_config.mask_prob

     __A	:       Any      =							"Wav2Vec2FeatureExtractor"
     __A	:       str      =							"Wav2Vec2CTCTokenizer"

     return config


@torch.no_grad()
def 		_lowercase (SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE=None       ,					SCREAMING_SNAKE_CASE=None       ,					SCREAMING_SNAKE_CASE=True							):




     '''simple docstring'''





     if is_finetuned:
          __A  ,__A  ,__A	:       Union[str, Any]      =							fairseq.checkpoint_utils.load_model_ensemble_and_task(
              [checkpoint_path]       ,					arg_overrides={"data": "/".join(dict_path.split("/"							)[:-1]							)}							)
     else:
          __A  ,__A  ,__A	:       Tuple      =							fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]							)

     if config_path is not None:
          __A	:       Optional[int]      =							SEWConfig.from_pretrained(SCREAMING_SNAKE_CASE							)
     else:
          __A	:       int      =							convert_config(model[0]       ,					SCREAMING_SNAKE_CASE							)
     __A	:       List[str]      =							model[0].eval()

     __A	:       str      =							True if config.feat_extract_norm == "layer" else False
     __A	:       Tuple      =							WavaVecaFeatureExtractor(
         feature_size=1       ,					sampling_rate=1_6000       ,					padding_value=0       ,					do_normalize=SCREAMING_SNAKE_CASE       ,					return_attention_mask=SCREAMING_SNAKE_CASE       ,					)

     if is_finetuned:
          if dict_path:
               __A	:       List[Any]      =							Dictionary.load(SCREAMING_SNAKE_CASE							)

               # important change bos & pad token id since CTC symbol is <pad> and
               # not <s> as in fairseq
               __A	:       List[str]      =							target_dict.pad_index
               __A	:       Any      =							target_dict.bos_index
               __A	:       Tuple      =							target_dict.pad_index
               __A	:       Tuple      =							target_dict.bos_index
               __A	:       str      =							target_dict.eos_index
               __A	:       Optional[Any]      =							len(target_dict.symbols							)
               __A	:       Optional[int]      =							os.path.join(SCREAMING_SNAKE_CASE       ,					"vocab.json"							)
               if not os.path.isdir(SCREAMING_SNAKE_CASE							):
                    logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(SCREAMING_SNAKE_CASE							)							)
                    return
               os.makedirs(SCREAMING_SNAKE_CASE       ,					exist_ok=SCREAMING_SNAKE_CASE							)
               with open(SCREAMING_SNAKE_CASE       ,					"w"       ,					encoding="utf-8"							) as vocab_handle:
                    json.dump(target_dict.indices       ,					SCREAMING_SNAKE_CASE							)
               __A	:       Optional[Any]      =							WavaVecaCTCTokenizer(
                   SCREAMING_SNAKE_CASE       ,					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=SCREAMING_SNAKE_CASE       ,					)
               __A	:       Optional[Any]      =							WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE       ,					tokenizer=SCREAMING_SNAKE_CASE							)
               processor.save_pretrained(SCREAMING_SNAKE_CASE							)

          __A	:       List[Any]      =							SEWForCTC(SCREAMING_SNAKE_CASE							)
     else:
          __A	:       Optional[Any]      =							SEWModel(SCREAMING_SNAKE_CASE							)
          feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE							)

     recursively_load_weights(SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE							)

     hf_model.save_pretrained(SCREAMING_SNAKE_CASE							)


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(
          """--is_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not"""
      )
      _UpperCamelCase 							=  parser.parse_args()
      convert_sew_checkpoint(
          args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned
      )





'''simple docstring'''


import math
import time

from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm
      import torch_xla.debug.metrics as met







class 							__magic_name__	(       lowerCAmelCase ):

     """simple docstring"""






     def __init__(   self			,     *lowerCamelCase			,     lowerCamelCase=None			,     lowerCamelCase=None			,     **lowerCamelCase		):


          '''simple docstring'''





          super().__init__(*lowerCamelCase			,     **lowerCamelCase		)
          __A	:       Tuple      =							eval_examples
          __A	:       List[str]      =							post_process_function


     def lowerCAmelCase__  (   self			,     lowerCamelCase=None			,     lowerCamelCase=None			,     lowerCamelCase=None			,     lowerCamelCase = "eval"		):


          '''simple docstring'''





          __A	:       Any      =							self.eval_dataset if eval_dataset is None else eval_dataset
          __A	:       Dict      =							self.get_eval_dataloader(lowerCamelCase		)
          __A	:       str      =							self.eval_examples if eval_examples is None else eval_examples

          # Temporarily disable metric computation, we will do it in the loop here.
          __A	:       Any      =							self.compute_metrics
          __A	:       Optional[int]      =							None
          __A	:       Tuple      =							self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
          __A	:       Dict      =							time.time()
          try:
               __A	:       List[str]      =							eval_loop(
                   lowerCamelCase			,     description="Evaluation"			,     prediction_loss_only=True if compute_metrics is None else None			,     ignore_keys=lowerCamelCase			,     metric_key_prefix=lowerCamelCase			,     )
          finally:
               __A	:       List[str]      =							compute_metrics
          __A	:       List[Any]      =							self.args.eval_batch_size * self.args.world_size
          if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
               start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
          output.metrics.update(
              speed_metrics(
                  lowerCamelCase			,     lowerCamelCase			,     num_samples=output.num_samples			,     num_steps=math.ceil(output.num_samples / total_batch_size		)			,     )		)
          if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
               # Only the main node write the results by default
               __A	:       List[Any]      =							self.post_process_function(lowerCamelCase			,     lowerCamelCase			,     output.predictions		)
               __A	:       List[str]      =							self.compute_metrics(lowerCamelCase		)

               # Prefix all keys with metric_key_prefix + '_'
               for key in list(metrics.keys()		):
                    if not key.startswith(f"{metric_key_prefix}_"		):
                         __A	:       Union[str, Any]      =							metrics.pop(lowerCamelCase		)
               metrics.update(output.metrics		)
          else:
               __A	:       Any      =							output.metrics

          if self.args.should_log:
               # Only the main node log the results by default
               self.log(lowerCamelCase		)

          if self.args.tpu_metrics_debug or self.args.debug:
               # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
               xm.master_print(met.metrics_report()		)

          __A	:       str      =							self.callback_handler.on_evaluate(self.args			,     self.state			,     self.control			,     lowerCamelCase		)
          return metrics


     def lowerCAmelCase__  (   self			,     lowerCamelCase			,     lowerCamelCase			,     lowerCamelCase=None			,     lowerCamelCase = "test"		):


          '''simple docstring'''





          __A	:       Tuple      =							self.get_test_dataloader(lowerCamelCase		)

          # Temporarily disable metric computation, we will do it in the loop here.
          __A	:       Union[str, Any]      =							self.compute_metrics
          __A	:       Union[str, Any]      =							None
          __A	:       Optional[Any]      =							self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
          __A	:       Tuple      =							time.time()
          try:
               __A	:       List[str]      =							eval_loop(
                   lowerCamelCase			,     description="Prediction"			,     prediction_loss_only=True if compute_metrics is None else None			,     ignore_keys=lowerCamelCase			,     metric_key_prefix=lowerCamelCase			,     )
          finally:
               __A	:       int      =							compute_metrics
          __A	:       List[Any]      =							self.args.eval_batch_size * self.args.world_size
          if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
               start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
          output.metrics.update(
              speed_metrics(
                  lowerCamelCase			,     lowerCamelCase			,     num_samples=output.num_samples			,     num_steps=math.ceil(output.num_samples / total_batch_size		)			,     )		)

          if self.post_process_function is None or self.compute_metrics is None:
               return output

          __A	:       Dict      =							self.post_process_function(lowerCamelCase			,     lowerCamelCase			,     output.predictions			,     "predict"		)
          __A	:       Tuple      =							self.compute_metrics(lowerCamelCase		)

          # Prefix all keys with metric_key_prefix + '_'
          for key in list(metrics.keys()		):
               if not key.startswith(f"{metric_key_prefix}_"		):
                    __A	:       Any      =							metrics.pop(lowerCamelCase		)
          metrics.update(output.metrics		)
          return PredictionOutput(predictions=predictions.predictions			,     label_ids=predictions.label_ids			,     metrics=lowerCamelCase		)

