





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

UpperCAmelCase	:	str		     =       {
    """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      _A       (		SCREAMING_SNAKE_CASE     :   List[Any]       ,       SCREAMING_SNAKE_CASE     :   Any       ,       SCREAMING_SNAKE_CASE     :   List[Any]       ,       SCREAMING_SNAKE_CASE     :   str       ,       SCREAMING_SNAKE_CASE     :   str						):





  """simple docstring"""



  for attribute in key.split("."						):
    a__	:					Tuple										=getattr(SCREAMING_SNAKE_CASE       ,       SCREAMING_SNAKE_CASE						)

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

  logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.'''						)
def      _A       (		SCREAMING_SNAKE_CASE     :   str       ,       SCREAMING_SNAKE_CASE     :   Optional[int]       ,       SCREAMING_SNAKE_CASE     :   List[str]						):





  """simple docstring"""



  a__	:					List[str]										=[]
  a__	:					Dict										=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__	:					Optional[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__	:					List[str]										=True
    else:
      for key, mapped_key in MAPPING.items():
        a__	:					str										="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__	:					str										=name.split(SCREAMING_SNAKE_CASE						)[0].split("."						)[-2]
            a__	:					List[str]										=mapped_key.replace("*"       ,       SCREAMING_SNAKE_CASE						)
          if "weight_g" in name:
            a__	:					List[str]										="weight_g"
          elif "weight_v" in name:
            a__	:					Optional[int]										="weight_v"
          elif "weight" in name:
            a__	:					Tuple										="weight"
          elif "bias" in name:
            a__	:					Optional[int]										="bias"
          else:
            a__	:					List[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      _A       (		SCREAMING_SNAKE_CASE     :   Dict       ,       SCREAMING_SNAKE_CASE     :   Dict       ,       SCREAMING_SNAKE_CASE     :   List[str]       ,       SCREAMING_SNAKE_CASE     :   int       ,       SCREAMING_SNAKE_CASE     :   Any						):





  """simple docstring"""



  a__	:					int										=full_name.split("conv_layers."						)[-1]
  a__	:					Union[str, Any]										=name.split("."						)
  a__	:					Tuple										=int(items[0]						)
  a__	:					Any										=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__	:					Any										=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__	:					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__	:					str										=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      _A       (		SCREAMING_SNAKE_CASE     :   Optional[Any]       ,       SCREAMING_SNAKE_CASE     :   Union[str, Any]						):





  """simple docstring"""



  a__	:					Optional[int]										=SEWConfig()
  if is_finetuned:
    a__	:					Optional[Any]										=model.wav_encoder.wav_model.cfg
  else:
    a__	:					int										=model.cfg

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

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

  a__	:					List[str]										="Wav2Vec2FeatureExtractor"
  a__	:					List[str]										="Wav2Vec2CTCTokenizer"

  return config
@torch.no_grad()
def      _A       (		SCREAMING_SNAKE_CASE     :   Dict       ,       SCREAMING_SNAKE_CASE     :   Tuple       ,       SCREAMING_SNAKE_CASE     :   str=None       ,       SCREAMING_SNAKE_CASE     :   Dict=None       ,       SCREAMING_SNAKE_CASE     :   List[str]=True						):





  """simple docstring"""



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

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

  a__	:					List[str]										=True if config.feat_extract_norm == "layer" else False
  a__	:					Optional[int]										=WavaVecaFeatureExtractor(
      feature_size=1       ,       sampling_rate=16_000       ,       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__	:					Any										=target_dict.pad_index
      a__	:					Any										=target_dict.bos_index
      a__	:					List[Any]										=target_dict.pad_index
      a__	:					Dict										=target_dict.bos_index
      a__	:					Optional[int]										=target_dict.eos_index
      a__	:					Dict										=len(target_dict.symbols						)
      a__	:					List[str]										=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__	:					List[Any]										=WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE       ,       tokenizer=SCREAMING_SNAKE_CASE						)
      processor.save_pretrained(SCREAMING_SNAKE_CASE						)

    a__	:					Optional[int]										=SEWForCTC(SCREAMING_SNAKE_CASE						)
  else:
    a__	:					int										=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	:	Optional[Any]		     =       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	:	Tuple		     =       parser.parse_args()
     convert_sew_checkpoint(
         args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned
     )













from queue import Queue
from typing import TYPE_CHECKING, Optional


if TYPE_CHECKING:
     from ..models.auto import AutoTokenizer







class 				__lowerCAmelCase       :







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						Optional[Any]:



        '''simple docstring'''




        raise NotImplementedError()







      def    _lowercase  (    self							)   ->						int:



        '''simple docstring'''




        raise NotImplementedError()







class 				__lowerCAmelCase       (    UpperCamelCase__):







      def __init__(    self		,      lowerCAmelCase__		,      lowerCAmelCase__ = False		,      **lowerCAmelCase__							)   ->						int:



        '''simple docstring'''




        a__	:					str										=tokenizer
        a__	:					List[str]										=skip_prompt
        a__	:					List[Any]										=decode_kwargs

        # variables used in the streaming process
        a__	:					Dict										=[]
        a__	:					int										=0
        a__	:					str										=True







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						Union[str, Any]:



        '''simple docstring'''




        if len(value.shape							) > 1 and value.shape[0] > 1:
          raise ValueError("TextStreamer only supports batch size 1"							)
        elif len(value.shape							) > 1:
          a__	:					Any										=value[0]

        if self.skip_prompt and self.next_tokens_are_prompt:
          a__	:					Dict										=False
          return

        # Add the new token to the cache and decodes the entire thing.
        self.token_cache.extend(value.tolist()							)
        a__	:					Union[str, Any]										=self.tokenizer.decode(self.token_cache		,      **self.decode_kwargs							)

        # After the symbol for a new line, we flush the cache.
        if text.endswith("\n"							):
          a__	:					List[Any]										=text[self.print_len :]
          a__	:					List[str]										=[]
          a__	:					Optional[int]										=0
        # If the last token is a CJK character, we print the characters.
        elif len(lowerCAmelCase__							) > 0 and self._is_chinese_char(ord(text[-1]							)							):
          a__	:					List[str]										=text[self.print_len :]
          self.print_len += len(lowerCAmelCase__							)
        # Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words,
        # which may change with the subsequent token -- there are probably smarter ways to do this!)
        else:
          a__	:					str										=text[self.print_len : text.rfind(" "							) + 1]
          self.print_len += len(lowerCAmelCase__							)

        self.on_finalized_text(lowerCAmelCase__							)







      def    _lowercase  (    self							)   ->						Any:



        '''simple docstring'''




        if len(self.token_cache							) > 0:
          a__	:					Union[str, Any]										=self.tokenizer.decode(self.token_cache		,      **self.decode_kwargs							)
          a__	:					List[Any]										=text[self.print_len :]
          a__	:					List[str]										=[]
          a__	:					Optional[int]										=0
        else:
          a__	:					Union[str, Any]										=""

        a__	:					Any										=True
        self.on_finalized_text(lowerCAmelCase__		,      stream_end=lowerCAmelCase__							)







      def    _lowercase  (    self		,      lowerCAmelCase__		,      lowerCAmelCase__ = False							)   ->						Optional[Any]:



        '''simple docstring'''




        print(lowerCAmelCase__		,      flush=lowerCAmelCase__		,      end="" if not stream_end else None							)







      def    _lowercase  (    self		,      lowerCAmelCase__							)   ->						str:



        '''simple docstring'''




        if (
            (cp >= 0X4E_00 and cp <= 0X9F_FF)
            or (cp >= 0X34_00 and cp <= 0X4D_BF)  #
            or (cp >= 0X2_00_00 and cp <= 0X2_A6_DF)  #
            or (cp >= 0X2_A7_00 and cp <= 0X2_B7_3F)  #
            or (cp >= 0X2_B7_40 and cp <= 0X2_B8_1F)  #
            or (cp >= 0X2_B8_20 and cp <= 0X2_CE_AF)  #
            or (cp >= 0XF9_00 and cp <= 0XFA_FF)
            or (cp >= 0X2_F8_00 and cp <= 0X2_FA_1F)  #
        ):  #
          return True

        return False







class 				__lowerCAmelCase       (    UpperCamelCase__):







      def __init__(    self		,      lowerCAmelCase__		,      lowerCAmelCase__ = False		,      lowerCAmelCase__ = None		,      **lowerCAmelCase__							)   ->						Optional[Any]:



        '''simple docstring'''




        super().__init__(lowerCAmelCase__		,      lowerCAmelCase__		,      **lowerCAmelCase__							)
        a__	:					str										=Queue()
        a__	:					Optional[Any]										=None
        a__	:					Any										=timeout







      def    _lowercase  (    self		,      lowerCAmelCase__		,      lowerCAmelCase__ = False							)   ->						List[str]:



        '''simple docstring'''




        self.text_queue.put(lowerCAmelCase__		,      timeout=self.timeout							)
        if stream_end:
          self.text_queue.put(self.stop_signal		,      timeout=self.timeout							)







      def __iter__(    self							)   ->						Dict:



        '''simple docstring'''




        return self







      def    _lowercase  (    self							)   ->						int:



        '''simple docstring'''




        a__	:					int										=self.text_queue.get(timeout=self.timeout							)
        if value == self.stop_signal:
          raise StopIteration()
        else:
          return value






