


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

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



def  _a			(						__UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase ):
     for attribute in key.split(""".""" ):
          a_    :     Union[str, Any]										=    getattr(__UpperCamelCase  ,  __UpperCamelCase )

     if weight_type is not None:
          a_    :     int										=    getattr(__UpperCamelCase  ,  __UpperCamelCase ).shape
     else:
          a_    :     List[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_    :     Tuple										=    value
     elif weight_type == "weight_g":
          a_    :     Dict										=    value
     elif weight_type == "weight_v":
          a_    :     List[Any]										=    value
     elif weight_type == "bias":
          a_    :     List[str]										=    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			(						__UpperCamelCase  ,  __UpperCamelCase ):
     a_    :     List[Any]										=    []
     a_    :     Dict										=    fairseq_model.state_dict()

     a_    :     List[Any]										=    hf_model.feature_extractor

     # if encoder has different dim to decoder -> use proj_weight
     a_    :     int										=    None

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

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

     return proj_weight



def  _a			(						__UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase ):
     a_    :     Union[str, Any]										=    full_name.split("""conv_layers.""" )[-1]
     a_    :     List[str]										=    name.split(""".""" )
     a_    :     str										=    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_    :     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_    :     str										=    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_    :     List[str]										=    value
               logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
     else:
          unused_weights.append(__UpperCamelCase )



def  _a			(						__UpperCamelCase ):
     a_			,			a_    :     List[str]										=    emb.weight.shape
     a_    :     int										=    nn.Linear(__UpperCamelCase  ,  __UpperCamelCase  ,  bias=__UpperCamelCase )
     a_    :     Dict										=    emb.weight.data
     return lin_layer



def  _a			(						__UpperCamelCase ):
     with open(__UpperCamelCase  ,  """r"""  ,  encoding="""utf-8""" ) as f:
          a_    :     str										=    f.readlines()
          a_    :     Dict										=    [line.split(""" """ )[0] for line in lines]

     a_    :     Dict										=    len(__UpperCamelCase )

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

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



@torch.no_grad()
def  _a			(						__UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase  ,  ):
     a_    :     List[Any]										=    WavaVecaConfig.from_pretrained(__UpperCamelCase )
     a_    :     Optional[int]										=    SpeechaTextaConfig.from_pretrained(
         __UpperCamelCase  ,  vocab_size=__UpperCamelCase  ,  decoder_layers=__UpperCamelCase  ,  do_stable_layer_norm=__UpperCamelCase )

     a_    :     Dict										=    WavaVecaFeatureExtractor(
         feature_size=1  ,  sampling_rate=1_6_0_0_0  ,  padding_value=0  ,  do_normalize=__UpperCamelCase  ,  return_attention_mask=__UpperCamelCase  ,  )

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

     # set weights for wav2vec2 encoder
     a_    :     int										=    WavaVecaModel(__UpperCamelCase )
     a_    :     Tuple										=    recursively_load_weights_wavaveca(model.encoder  ,  __UpperCamelCase )

     a_    :     Optional[int]										=    SpeechaTextaForCausalLM(__UpperCamelCase )
     a_			,			a_    :     List[Any]										=    hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict()  ,  strict=__UpperCamelCase )

     # set output linear layer
     unexpected_keys.remove("""embed_out""" )
     a_    :     List[str]										=    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}''' )

     a_    :     int										=    SpeechEncoderDecoderModel(encoder=__UpperCamelCase  ,  decoder=__UpperCamelCase )
     a_    :     str										=    False

     # add projection layer
     a_    :     str										=    nn.Parameter(projection_layer.weight )
     a_    :     List[Any]										=    nn.Parameter(projection_layer.bias )

     a_    :     List[Any]										=    create_vocab_dict(__UpperCamelCase )

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

     a_    :     List[Any]										=    SpeechaTextaTokenizer(os.path.join(__UpperCamelCase  ,  """vocab.json""" ) )
     tokenizer.save_pretrained(__UpperCamelCase )

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

     a_    :     str										=    SpeechEncoderDecoderConfig.from_dict(__UpperCamelCase )

     hf_wavavec.save_pretrained(__UpperCamelCase )
     feature_extractor.save_pretrained(__UpperCamelCase )


if __name__ == "__main__":
       __lowerCamelCase        =     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=10224, type=int, help='''Vocab size of decoder''')
       parser.add_argument('''--num_decoder_layers''', default=7, type=int, help='''Number of decoder layers''')

       __lowerCamelCase        =     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,
       )







from __future__ import annotations

import random

# Maximum size of the population.  Bigger could be faster but is more memory expensive.
__lowerCamelCase        =     200
# Number of elements selected in every generation of evolution. The selection takes
# place from best to worst of that generation and must be smaller than N_POPULATION.
__lowerCamelCase        =     50
# Probability that an element of a generation can mutate, changing one of its genes.
# This will guarantee that all genes will be used during evolution.
__lowerCamelCase        =     0.4
# Just a seed to improve randomness required by the algorithm.
random.seed(random.randint(0, 1000))



def  _a			(						__UpperCamelCase  ,  __UpperCamelCase ):
     a_    :     List[Any]										=    len([g for position, g in enumerate(__UpperCamelCase ) if g == main_target[position]] )
     return (item, float(__UpperCamelCase ))



def  _a			(						__UpperCamelCase  ,  __UpperCamelCase ):
     a_    :     List[Any]										=    random.randint(0  ,  len(__UpperCamelCase ) - 1 )
     a_    :     Tuple										=    parent_a[:random_slice] + parent_a[random_slice:]
     a_    :     Optional[Any]										=    parent_a[:random_slice] + parent_a[random_slice:]
     return (child_a, child_a)



def  _a			(						__UpperCamelCase  ,  __UpperCamelCase ):
     a_    :     Optional[int]										=    list(__UpperCamelCase )
     if random.uniform(0  ,  1 ) < MUTATION_PROBABILITY:
          a_    :     int										=    random.choice(__UpperCamelCase )
     return "".join(__UpperCamelCase )



def  _a			(						__UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase  ,  ):
     a_    :     Tuple										=    []
     # Generate more children proportionally to the fitness score.
     a_    :     Any										=    int(parent_a[1] * 1_0_0 ) + 1
     a_    :     int										=    1_0 if child_n >= 1_0 else child_n
     for _ in range(__UpperCamelCase ):
          a_    :     Tuple										=    population_score[random.randint(0  ,  __UpperCamelCase )][0]

          a_			,			a_    :     List[str]										=    crossover(parent_a[0]  ,  __UpperCamelCase )
          # Append new string to the population list.
          pop.append(mutate(__UpperCamelCase  ,  __UpperCamelCase ) )
          pop.append(mutate(__UpperCamelCase  ,  __UpperCamelCase ) )
     return pop



def  _a			(						__UpperCamelCase  ,  __UpperCamelCase  ,  __UpperCamelCase = True ):

     # Verify if N_POPULATION is bigger than N_SELECTED
     if N_POPULATION < N_SELECTED:
          a_    :     Union[str, Any]										=    F'''{N_POPULATION} must be bigger than {N_SELECTED}'''
          raise ValueError(__UpperCamelCase )
     # Verify that the target contains no genes besides the ones inside genes variable.
     a_    :     List[str]										=    sorted({c for c in target if c not in genes} )
     if not_in_genes_list:
          a_    :     Optional[Any]										=    F'''{not_in_genes_list} is not in genes list, evolution cannot converge'''
          raise ValueError(__UpperCamelCase )

     # Generate random starting population.
     a_    :     str										=    []
     for _ in range(__UpperCamelCase ):
          population.append("""""".join([random.choice(__UpperCamelCase ) for i in range(len(__UpperCamelCase ) )] ) )

     # Just some logs to know what the algorithms is doing.
     a_			,			a_    :     List[str]										=    0, 0

     # This loop will end when we find a perfect match for our target.
     while True:
          generation += 1
          total_population += len(__UpperCamelCase )

          # Random population created. Now it's time to evaluate.

          # Adding a bit of concurrency can make everything faster,
          #
          # import concurrent.futures
          # population_score: list[tuple[str, float]] = []
          # with concurrent.futures.ThreadPoolExecutor(
          #                                   max_workers=NUM_WORKERS) as executor:
          #     futures = {executor.submit(evaluate, item) for item in population}
          #     concurrent.futures.wait(futures)
          #     population_score = [item.result() for item in futures]
          #
          # but with a simple algorithm like this, it will probably be slower.
          # We just need to call evaluate for every item inside the population.
          a_    :     Tuple										=    [evaluate(__UpperCamelCase  ,  __UpperCamelCase ) for item in population]

          # Check if there is a matching evolution.
          a_    :     Optional[Any]										=    sorted(__UpperCamelCase  ,  key=lambda __UpperCamelCase : x[1]  ,  reverse=__UpperCamelCase )
          if population_score[0][0] == target:
               return (generation, total_population, population_score[0][0])

          # Print the best result every 10 generation.
          # Just to know that the algorithm is working.
          if debug and generation % 1_0 == 0:
               print(
                   F'''\nGeneration: {generation}'''
                   F'''\nTotal Population:{total_population}'''
                   F'''\nBest score: {population_score[0][1]}'''
                   F'''\nBest string: {population_score[0][0]}''' )

          # Flush the old population, keeping some of the best evolutions.
          # Keeping this avoid regression of evolution.
          a_    :     List[str]										=    population[: int(N_POPULATION / 3 )]
          population.clear()
          population.extend(__UpperCamelCase )
          # Normalize population score to be between 0 and 1.
          a_    :     Optional[Any]										=    [
              (item, score / len(__UpperCamelCase )) for item, score in population_score
          ]

          # This is selection
          for i in range(__UpperCamelCase ):
               population.extend(select(population_score[int(__UpperCamelCase )]  ,  __UpperCamelCase  ,  __UpperCamelCase ) )
               # Check if the population has already reached the maximum value and if so,
               # break the cycle.  If this check is disabled, the algorithm will take
               # forever to compute large strings, but will also calculate small strings in
               # a far fewer generations.
               if len(__UpperCamelCase ) > N_POPULATION:
                    break


if __name__ == "__main__":
       __lowerCamelCase        =     (
           '''This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!'''
       )
       __lowerCamelCase        =     list(
           ''' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm'''
           '''nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\'''
       )
       __lowerCamelCase  ,       __lowerCamelCase  ,       __lowerCamelCase        =     basic(target_str, genes_list)
       print(
           f'''\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}'''
       )



