
'''simple docstring'''





import argparse
import json
import os

import fairseq
import torch
from torch import nn

from transformers import (
    SpeechaTextaConfig,
    SpeechaTextaForCausalLM,
    SpeechaTextaTokenizer,
    SpeechEncoderDecoderConfig,
    SpeechEncoderDecoderModel,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaModel,
    logging,
)


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

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







def snake_case_     (					lowercase__   ,       lowercase__   ,       lowercase__   ,       lowercase__   ,       lowercase__		):
  for attribute in key.split("."		):
    UpperCAmelCase__      :					List[Any]				       =							getattr(lowercase__   ,       lowercase__		)

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

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







def snake_case_     (					lowercase__   ,       lowercase__		):
  UpperCAmelCase__      :					Tuple				       =							[]
  UpperCAmelCase__      :					Any				       =							fairseq_model.state_dict()

  UpperCAmelCase__      :					Union[str, Any]				       =							hf_model.feature_extractor

  # if encoder has different dim to decoder -> use proj_weight
  UpperCAmelCase__      :					Union[str, Any]				       =							None

  for name, value in fairseq_dict.items():
    UpperCAmelCase__      :					Tuple				       =							False
    if "conv_layers" in name:
      load_conv_layer(
          lowercase__   ,       lowercase__   ,       lowercase__   ,       lowercase__   ,       hf_model.config.feat_extract_norm == "group"   ,       )
      UpperCAmelCase__      :					Dict				       =							True
    elif name.split("."		)[0] == "proj":
      UpperCAmelCase__      :					List[Any]				       =							fairseq_model.proj
      UpperCAmelCase__      :					Union[str, Any]				       =							True
    else:
      for key, mapped_key in MAPPING.items():
        if key in name or key.split("w2v_model."		)[-1] == name.split("."		)[0]:
          UpperCAmelCase__      :					Optional[int]				       =							True
          if "*" in mapped_key:
            UpperCAmelCase__      :					Union[str, Any]				       =							name.split(lowercase__		)[0].split("."		)[-2]
            UpperCAmelCase__      :					List[str]				       =							mapped_key.replace("*"   ,       lowercase__		)
          if "weight_g" in name:
            UpperCAmelCase__      :					List[Any]				       =							"weight_g"
          elif "weight_v" in name:
            UpperCAmelCase__      :					int				       =							"weight_v"
          elif "bias" in name:
            UpperCAmelCase__      :					Any				       =							"bias"
          elif "weight" in name:
            UpperCAmelCase__      :					int				       =							"weight"
          else:
            UpperCAmelCase__      :					Union[str, Any]				       =							None
          set_recursively(lowercase__   ,       lowercase__   ,       lowercase__   ,       lowercase__   ,       lowercase__		)
        continue
    if not is_used:
      unused_weights.append(lowercase__		)

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

  return proj_weight







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







def snake_case_     (					lowercase__		):
  UpperCAmelCase__       ,			UpperCAmelCase__      :					Optional[Any]				       =							emb.weight.shape
  UpperCAmelCase__      :					Union[str, Any]				       =							nn.Linear(lowercase__   ,       lowercase__   ,       bias=lowercase__		)
  UpperCAmelCase__      :					str				       =							emb.weight.data
  return lin_layer







def snake_case_     (					lowercase__		):
  with open(lowercase__   ,       "r"   ,       encoding="utf-8"		) as f:
    UpperCAmelCase__      :					int				       =							f.readlines()
    UpperCAmelCase__      :					List[str]				       =							[line.split(" "		)[0] for line in lines]

  UpperCAmelCase__      :					int				       =							len(lowercase__		)

  UpperCAmelCase__      :					List[Any]				       =							{
      "<s>": 0,
      "<pad>": 1,
      "</s>": 2,
      "<unk>": 3,
  }

  vocab_dict.update(dict(zip(lowercase__   ,       range(4   ,       num_words + 4		)		)		)		)
  return vocab_dict







@torch.no_grad()
def snake_case_     (					lowercase__   ,       lowercase__   ,       lowercase__   ,       lowercase__   ,       lowercase__   ,       lowercase__   ,       lowercase__   ,       ):
  UpperCAmelCase__      :					Optional[Any]				       =							WavaVecaConfig.from_pretrained(lowercase__		)
  UpperCAmelCase__      :					List[str]				       =							SpeechaTextaConfig.from_pretrained(
      lowercase__   ,       vocab_size=lowercase__   ,       decoder_layers=lowercase__   ,       do_stable_layer_norm=lowercase__		)

  UpperCAmelCase__      :					Optional[Any]				       =							WavaVecaFeatureExtractor(
      feature_size=1   ,       sampling_rate=1_6_0_0_0   ,       padding_value=0   ,       do_normalize=lowercase__   ,       return_attention_mask=lowercase__   ,       )

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

  # set weights for wav2vec2 encoder
  UpperCAmelCase__      :					Optional[int]				       =							WavaVecaModel(lowercase__		)
  UpperCAmelCase__      :					Union[str, Any]				       =							recursively_load_weights_wavaveca(model.encoder   ,       lowercase__		)

  UpperCAmelCase__      :					Optional[Any]				       =							SpeechaTextaForCausalLM(lowercase__		)
  UpperCAmelCase__       ,			UpperCAmelCase__      :					Any				       =							hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict()   ,       strict=lowercase__		)

  # set output linear layer
  unexpected_keys.remove("embed_out"		)
  UpperCAmelCase__      :					Dict				       =							nn.Parameter(model.decoder.embed_out.detach()		)

  # layer norm is init to identity matrix so leaving it is fine
  logger.warning(F"""The following keys are missing when loading the decoder weights: {missing_keys}"""		)
  logger.warning(F"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}"""		)

  UpperCAmelCase__      :					int				       =							SpeechEncoderDecoderModel(encoder=lowercase__   ,       decoder=lowercase__		)
  UpperCAmelCase__      :					Dict				       =							False

  # add projection layer
  UpperCAmelCase__      :					Union[str, Any]				       =							nn.Parameter(projection_layer.weight		)
  UpperCAmelCase__      :					int				       =							nn.Parameter(projection_layer.bias		)

  UpperCAmelCase__      :					Tuple				       =							create_vocab_dict(lowercase__		)

  with open(os.path.join(lowercase__   ,       "vocab.json"		)   ,       "w"		) as fp:
    json.dump(lowercase__   ,       lowercase__		)

  UpperCAmelCase__      :					Optional[Any]				       =							SpeechaTextaTokenizer(os.path.join(lowercase__   ,       "vocab.json"		)		)
  tokenizer.save_pretrained(lowercase__		)

  UpperCAmelCase__      :					Optional[int]				       =							hf_wavavec.config.to_dict()
  UpperCAmelCase__      :					List[str]				       =							tokenizer.pad_token_id
  UpperCAmelCase__      :					Optional[int]				       =							tokenizer.bos_token_id
  UpperCAmelCase__      :					Optional[int]				       =							tokenizer.eos_token_id
  UpperCAmelCase__      :					Union[str, Any]				       =							"speech_to_text_2"
  UpperCAmelCase__      :					Tuple				       =							"wav2vec2"

  UpperCAmelCase__      :					Union[str, Any]				       =							SpeechEncoderDecoderConfig.from_dict(lowercase__		)

  hf_wavavec.save_pretrained(lowercase__		)
  feature_extractor.save_pretrained(lowercase__		)


if __name__ == "__main__":
      SCREAMING_SNAKE_CASE     =       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(
          """--encoder_config_path""",
          default="""facebook/wav2vec2-large-lv60""",
          type=str,
          help="""Path to hf encoder wav2vec2 checkpoint config""",
      )
      parser.add_argument(
          """--decoder_config_path""",
          default="""facebook/s2t-small-mustc-en-fr-st""",
          type=str,
          help="""Path to hf decoder s2t checkpoint config""",
      )
      parser.add_argument("""--vocab_size""", default=1_0_2_2_4, type=int, help="""Vocab size of decoder""")
      parser.add_argument("""--num_decoder_layers""", default=7, type=int, help="""Number of decoder layers""")

      SCREAMING_SNAKE_CASE     =       parser.parse_args()
      convert_wavaveca_checkpoint(
          args.checkpoint_path,
          args.pytorch_dump_folder_path,
          args.dict_path,
          encoder_config_path=args.encoder_config_path,
          decoder_config_path=args.decoder_config_path,
          vocab_size=args.vocab_size,
          num_decoder_layers=args.num_decoder_layers,
      )





'''simple docstring'''





import math







def snake_case_     (					lowercase__		):

  if 1 < number < 4:
    # 2 and 3 are primes
    return True
  elif number < 2 or number % 2 == 0 or number % 3 == 0:
    # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
    return False

  # All primes number are in format of 6k +/- 1
  for i in range(5   ,       int(math.sqrt(lowercase__		) + 1		)   ,       6		):
    if number % i == 0 or number % (i + 2) == 0:
      return False
  return True







def snake_case_     (					lowercase__ = 0.1		):
  UpperCAmelCase__      :					Dict				       =							3
  UpperCAmelCase__      :					Tuple				       =							3

  while primes / (2 * j - 1) >= ratio:
    for i in range(j * j + j + 1   ,       (j + 2) * (j + 2)   ,       j + 1		):
      primes += is_prime(lowercase__		)
    j += 2
  return j


if __name__ == "__main__":
      import doctest

      doctest.testmod()



