'''simple docstring'''




import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import SPIECE_UNDERLINE, logging


__UpperCAmelCase												=logging.get_logger(__name__)

__UpperCAmelCase												={"vocab_file": "spiece.model"}

__UpperCAmelCase												={
    "vocab_file": {
        "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model",
        "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model",
    }
}

__UpperCAmelCase												={
    "xlnet-base-cased": None,
    "xlnet-large-cased": None,
}

# Segments (not really needed)
__UpperCAmelCase												=0
__UpperCAmelCase												=1
__UpperCAmelCase												=2
__UpperCAmelCase												=3
__UpperCAmelCase												=4




class    a__				(       UpperCAmelCase__			):
     lowerCamelCase  :					List[str]							=VOCAB_FILES_NAMES
     lowerCamelCase  :					Optional[int]							=PRETRAINED_VOCAB_FILES_MAP
     lowerCamelCase  :					List[str]							=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     lowerCamelCase  :					List[Any]							="left"






     def __init__(			self		:		List[Any]  ,    a		:		str  ,    a		:		str=False  ,    a		:		Tuple=True  ,    a		:		Dict=False  ,    a		:		List[Any]="<s>"  ,    a		:		Dict="</s>"  ,    a		:		List[Any]="<unk>"  ,    a		:		Any="<sep>"  ,    a		:		List[Any]="<pad>"  ,    a		:		Optional[int]="<cls>"  ,    a		:		str="<mask>"  ,    a		:		Dict=["<eop>", "<eod>"]  ,    a		:		Optional[Dict[str, Any]] = None  ,    **a		:		Any  ,    ):





         """simple docstring"""



         __lowerCamelCase          =  AddedToken(a  ,    lstrip=a  ,    rstrip=a   ) if isinstance(a  ,    a   ) else mask_token

         __lowerCamelCase          =  {} if sp_model_kwargs is None else sp_model_kwargs

         super().__init__(
             do_lower_case=a  ,    remove_space=a  ,    keep_accents=a  ,    bos_token=a  ,    eos_token=a  ,    unk_token=a  ,    sep_token=a  ,    pad_token=a  ,    cls_token=a  ,    mask_token=a  ,    additional_special_tokens=a  ,    sp_model_kwargs=self.sp_model_kwargs  ,    **a  ,    )

         __lowerCamelCase          =  3

         __lowerCamelCase          =  do_lower_case
         __lowerCamelCase          =  remove_space
         __lowerCamelCase          =  keep_accents
         __lowerCamelCase          =  vocab_file

         __lowerCamelCase          =  spm.SentencePieceProcessor(**self.sp_model_kwargs   )
         self.sp_model.Load(a   )






     @property
     def        SCREAMING_SNAKE_CASE__       (			self		:		Dict   ):





         """simple docstring"""



         return len(self.sp_model   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		int   ):





         """simple docstring"""



         __lowerCamelCase          =  {self.convert_ids_to_tokens(a   ): i for i in range(self.vocab_size   )}
         vocab.update(self.added_tokens_encoder   )
         return vocab






     def __getstate__(			self		:		Any   ):





         """simple docstring"""



         __lowerCamelCase          =  self.__dict__.copy()
         __lowerCamelCase          =  None
         return state






     def __setstate__(			self		:		Optional[Any]  ,    a		:		List[str]   ):





         """simple docstring"""



         __lowerCamelCase          =  d

         # for backward compatibility
         if not hasattr(self  ,    '''sp_model_kwargs'''   ):
             __lowerCamelCase          =  {}

         __lowerCamelCase          =  spm.SentencePieceProcessor(**self.sp_model_kwargs   )
         self.sp_model.Load(self.vocab_file   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		str  ,    a		:		int   ):





         """simple docstring"""



         if self.remove_space:
             __lowerCamelCase          =  ''' '''.join(inputs.strip().split()   )
         else:
             __lowerCamelCase          =  inputs
         __lowerCamelCase          =  outputs.replace('''``'''  ,    '''"'''   ).replace('''\'\''''  ,    '''"'''   )

         if not self.keep_accents:
             __lowerCamelCase          =  unicodedata.normalize('''NFKD'''  ,    a   )
             __lowerCamelCase          =  ''''''.join([c for c in outputs if not unicodedata.combining(a   )]   )
         if self.do_lower_case:
             __lowerCamelCase          =  outputs.lower()

         return outputs






     def        SCREAMING_SNAKE_CASE__       (			self		:		int  ,    a		:		str   ):





         """simple docstring"""



         __lowerCamelCase          =  self.preprocess_text(a   )
         __lowerCamelCase          =  self.sp_model.encode(a  ,    out_type=a   )
         __lowerCamelCase          =  []
         for piece in pieces:
             if len(a   ) > 1 and piece[-1] == str(''','''   ) and piece[-2].isdigit():
                 __lowerCamelCase          =  self.sp_model.EncodeAsPieces(piece[:-1].replace(a  ,    ''''''   )   )
                 if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
                     if len(cur_pieces[0]   ) == 1:
                         __lowerCamelCase          =  cur_pieces[1:]
                     else:
                         __lowerCamelCase          =  cur_pieces[0][1:]
                 cur_pieces.append(piece[-1]   )
                 new_pieces.extend(a   )
             else:
                 new_pieces.append(a   )

         return new_pieces






     def        SCREAMING_SNAKE_CASE__       (			self		:		Dict  ,    a		:		List[str]   ):





         """simple docstring"""



         return self.sp_model.PieceToId(a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[Any]  ,    a		:		Union[str, Any]   ):





         """simple docstring"""



         return self.sp_model.IdToPiece(a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		Any  ,    a		:		List[Any]   ):





         """simple docstring"""



         __lowerCamelCase          =  ''''''.join(a   ).replace(a  ,    ''' '''   ).strip()
         return out_string






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]  ,    a		:		List[int]  ,    a		:		bool = False  ,    a		:		bool = None  ,    a		:		bool = True  ,    **a		:		Tuple  ,    ):





         """simple docstring"""



         __lowerCamelCase          =  kwargs.pop('''use_source_tokenizer'''  ,    a   )

         __lowerCamelCase          =  self.convert_ids_to_tokens(a  ,    skip_special_tokens=a   )

         # To avoid mixing byte-level and unicode for byte-level BPT
         # we need to build string separately for added tokens and byte-level tokens
         # cf. https://github.com/huggingface/transformers/issues/1133
         __lowerCamelCase          =  []
         __lowerCamelCase          =  []
         for token in filtered_tokens:
             if skip_special_tokens and token in self.all_special_ids:
                 continue
             if token in self.added_tokens_encoder:
                 if current_sub_text:
                     sub_texts.append(self.convert_tokens_to_string(a   )   )
                     __lowerCamelCase          =  []
                 sub_texts.append(a   )
             else:
                 current_sub_text.append(a   )
         if current_sub_text:
             sub_texts.append(self.convert_tokens_to_string(a   )   )

         # Mimic the behavior of the Rust tokenizer:
         # By default, there are no spaces between special tokens
         __lowerCamelCase          =  ''''''.join(a   )

         __lowerCamelCase          =  (
             clean_up_tokenization_spaces
             if clean_up_tokenization_spaces is not None
             else self.clean_up_tokenization_spaces
         )
         if clean_up_tokenization_spaces:
             __lowerCamelCase          =  self.clean_up_tokenization(a   )
             return clean_text
         else:
             return text






     def        SCREAMING_SNAKE_CASE__       (			self		:		Dict  ,    a		:		List[int]  ,    a		:		Optional[List[int]] = None   ):





         """simple docstring"""



         __lowerCamelCase          =  [self.sep_token_id]
         __lowerCamelCase          =  [self.cls_token_id]
         if token_ids_a is None:
             return token_ids_a + sep + cls
         return token_ids_a + sep + token_ids_a + sep + cls






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[Any]  ,    a		:		List[int]  ,    a		:		Optional[List[int]] = None  ,    a		:		bool = False   ):





         """simple docstring"""



         if already_has_special_tokens:
             return super().get_special_tokens_mask(
                 token_ids_a=a  ,    token_ids_a=a  ,    already_has_special_tokens=a   )

         if token_ids_a is not None:
             return ([0] * len(a   )) + [1] + ([0] * len(a   )) + [1, 1]
         return ([0] * len(a   )) + [1, 1]






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]  ,    a		:		List[int]  ,    a		:		Optional[List[int]] = None   ):





         """simple docstring"""



         __lowerCamelCase          =  [self.sep_token_id]
         __lowerCamelCase          =  [2]

         if token_ids_a is None:
             return len(token_ids_a + sep   ) * [0] + cls_segment_id
         return len(token_ids_a + sep   ) * [0] + len(token_ids_a + sep   ) * [1] + cls_segment_id






     def        SCREAMING_SNAKE_CASE__       (			self		:		Dict  ,    a		:		str  ,    a		:		Optional[str] = None   ):





         """simple docstring"""



         if not os.path.isdir(a   ):
             logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""   )
             return
         __lowerCamelCase          =  os.path.join(
             a  ,    (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']   )

         if os.path.abspath(self.vocab_file   ) != os.path.abspath(a   ) and os.path.isfile(self.vocab_file   ):
             copyfile(self.vocab_file  ,    a   )
         elif not os.path.isfile(self.vocab_file   ):
             with open(a  ,    '''wb'''   ) as fi:
                 __lowerCamelCase          =  self.sp_model.serialized_model_proto()
                 fi.write(a   )

         return (out_vocab_file,)

'''simple docstring'''




import argparse

import fairseq
import torch

from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, 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.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",
    "encoder.layer_norm_for_extract": "layer_norm_for_extract",
    "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",
    "label_embs_concat": "label_embeddings_concat",
    "mask_emb": "masked_spec_embed",
    "spk_proj": "speaker_proj",
}
__UpperCAmelCase												=[
    "lm_head",
    "quantizer.weight_proj",
    "quantizer.codevectors",
    "project_q",
    "project_hid",
    "label_embeddings_concat",
    "speaker_proj",
    "layer_norm_for_extract",
]






def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    )     ->   Any:
    for attribute in key.split('''.'''    ):
        __lowerCamelCase          =  getattr(UpperCamelCase__    ,  UpperCamelCase__    )

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

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






def __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__    )     ->   List[Any]:
    __lowerCamelCase          =  []
    __lowerCamelCase          =  fairseq_model.state_dict()

    __lowerCamelCase          =  hf_model.unispeech_sat.feature_extractor

    for name, value in fairseq_dict.items():
        __lowerCamelCase          =  False
        if "conv_layers" in name:
            load_conv_layer(
                UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    ,  hf_model.config.feat_extract_norm == '''group'''    ,  )
            __lowerCamelCase          =  True
        else:
            for key, mapped_key in MAPPING.items():
                __lowerCamelCase          =  '''unispeech_sat.''' + 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]:
                    if "layer_norm_for_extract" in name and (".".join(name.split('''.'''    )[:-1]    ) != key):
                        # special case since naming is very similar
                        continue
                    __lowerCamelCase          =  True
                    if "*" in mapped_key:
                        __lowerCamelCase          =  name.split(UpperCamelCase__    )[0].split('''.'''    )[-2]
                        __lowerCamelCase          =  mapped_key.replace('''*'''    ,  UpperCamelCase__    )
                    if "weight_g" in name:
                        __lowerCamelCase          =  '''weight_g'''
                    elif "weight_v" in name:
                        __lowerCamelCase          =  '''weight_v'''
                    elif "bias" in name:
                        __lowerCamelCase          =  '''bias'''
                    elif "weight" in name:
                        # TODO: don't match quantizer.weight_proj
                        __lowerCamelCase          =  '''weight'''
                    else:
                        __lowerCamelCase          =  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 __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__    )     ->   Any:
    __lowerCamelCase          =  full_name.split('''conv_layers.'''    )[-1]
    __lowerCamelCase          =  name.split('''.'''    )
    __lowerCamelCase          =  int(items[0]    )
    __lowerCamelCase          =  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."""    )
            __lowerCamelCase          =  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."""    )
            __lowerCamelCase          =  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[layer_id].layer_norm.bias.data.shape} was found."""    )
            __lowerCamelCase          =  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[layer_id].layer_norm.weight.data.shape} was found."""    )
            __lowerCamelCase          =  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 __lowerCAmelCase			(							UpperCamelCase__    ,  UpperCamelCase__    ,  UpperCamelCase__=None    ,  UpperCamelCase__=None    ,  UpperCamelCase__=True    )     ->   Optional[Any]:
    if config_path is not None:
        __lowerCamelCase          =  UniSpeechSatConfig.from_pretrained(UpperCamelCase__    )
    else:
        __lowerCamelCase          =  UniSpeechSatConfig()

    __lowerCamelCase          =  ''''''

    if is_finetuned:
        __lowerCamelCase          =  UniSpeechSatForCTC(UpperCamelCase__    )
    else:
        __lowerCamelCase          =  UniSpeechSatForPreTraining(UpperCamelCase__    )

    __lowerCamelCase     ,  __lowerCamelCase     ,  __lowerCamelCase          =  fairseq.checkpoint_utils.load_model_ensemble_and_task(
        [checkpoint_path]    ,  arg_overrides={'''data''': '''/'''.join(dict_path.split('''/'''    )[:-1]    )}    )
    __lowerCamelCase          =  model[0].eval()

    recursively_load_weights(UpperCamelCase__    ,  UpperCamelCase__    )

    hf_wavavec.save_pretrained(UpperCamelCase__    )


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