


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

__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""",
}
__snake_case    						=[
    """lm_head""",
    """quantizer.weight_proj""",
    """quantizer.codevectors""",
    """project_q""",
    """project_hid""",
]





def 	a_					( lowerCamelCase	:     Any	, lowerCamelCase	:     Dict	, lowerCamelCase	:     int	, lowerCamelCase	:     List[Any]	, lowerCamelCase	:     str				):
   for attribute in key.split('.'				):
      lowerCAmelCase     =			getattr(lowerCamelCase	, lowerCamelCase				)

   if weight_type is not None:
      lowerCAmelCase     =			getattr(lowerCamelCase	, lowerCamelCase				).shape
   else:
      lowerCAmelCase     =			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":
      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 	a_					( lowerCamelCase	:     Optional[int]	, lowerCamelCase	:     Any				):
   lowerCAmelCase     =			[]
   lowerCAmelCase     =			fairseq_model.state_dict()

   lowerCAmelCase     =			hf_model.feature_extractor

   # if encoder has different dim to decoder -> use proj_weight
   lowerCAmelCase     =			None

   for name, value in fairseq_dict.items():
      lowerCAmelCase     =			False
      if "conv_layers" in name:
         load_conv_layer(
             lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, hf_model.config.feat_extract_norm == 'group'	, )
         lowerCAmelCase     =			True
      elif name.split('.'				)[0] == "proj":
         lowerCAmelCase     =			fairseq_model.proj
         lowerCAmelCase     =			True
      else:
         for key, mapped_key in MAPPING.items():
            if key in name or key.split('w2v_model.'				)[-1] == name.split('.'				)[0]:
               lowerCAmelCase     =			True
               if "*" in mapped_key:
                  lowerCAmelCase     =			name.split(lowerCamelCase				)[0].split('.'				)[-2]
                  lowerCAmelCase     =			mapped_key.replace('*'	, lowerCamelCase				)
               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:
                  lowerCAmelCase     =			'weight'
               else:
                  lowerCAmelCase     =			None
               set_recursively(lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, lowerCamelCase	, lowerCamelCase				)
            continue
      if not is_used:
         unused_weights.append(lowerCamelCase				)

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

   return proj_weight





def 	a_					( lowerCamelCase	:     List[str]	, lowerCamelCase	:     List[str]	, lowerCamelCase	:     Dict	, lowerCamelCase	:     List[str]	, lowerCamelCase	:     Optional[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:
         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.'''
         )
         lowerCAmelCase     =			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.'''
         )
         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:
         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."
         )
         lowerCAmelCase     =			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.'''
         )
         lowerCAmelCase     =			value
         logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''				)
   else:
      unused_weights.append(lowerCamelCase				)





def 	a_					( lowerCamelCase	:     List[str]				):
   lowerCAmelCase     ,  lowerCAmelCase     =			emb.weight.shape
   lowerCAmelCase     =			nn.Linear(lowerCamelCase	, lowerCamelCase	, bias=lowerCamelCase				)
   lowerCAmelCase     =			emb.weight.data
   return lin_layer





def 	a_					( lowerCamelCase	:     Optional[int]				):
   with open(lowerCamelCase	, 'r'	, encoding='utf-8'				) as f:
      lowerCAmelCase     =			f.readlines()
      lowerCAmelCase     =			[line.split(' '				)[0] for line in lines]

   lowerCAmelCase     =			len(lowerCamelCase				)

   lowerCAmelCase     =			{
       '<s>': 0,
       '<pad>': 1,
       '</s>': 2,
       '<unk>': 3,
   }

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





@torch.no_grad()
def 	a_					( lowerCamelCase	:     str	, lowerCamelCase	:     Any	, lowerCamelCase	:     List[Any]	, lowerCamelCase	:     Any	, lowerCamelCase	:     Dict	, lowerCamelCase	:     Union[str, Any]	, lowerCamelCase	:     Tuple	, ):
   lowerCAmelCase     =			WavaVecaConfig.from_pretrained(lowerCamelCase				)
   lowerCAmelCase     =			SpeechaTextaConfig.from_pretrained(
       lowerCamelCase	, vocab_size=lowerCamelCase	, decoder_layers=lowerCamelCase	, do_stable_layer_norm=lowerCamelCase				)

   lowerCAmelCase     =			WavaVecaFeatureExtractor(
       feature_size=1	, sampling_rate=16000	, padding_value=0	, do_normalize=lowerCamelCase	, return_attention_mask=lowerCamelCase	, )

   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()

   # set weights for wav2vec2 encoder
   lowerCAmelCase     =			WavaVecaModel(lowerCamelCase				)
   lowerCAmelCase     =			recursively_load_weights_wavaveca(model.encoder	, lowerCamelCase				)

   lowerCAmelCase     =			SpeechaTextaForCausalLM(lowerCamelCase				)
   lowerCAmelCase     ,  lowerCAmelCase     =			hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict()	, strict=lowerCamelCase				)

   # set output linear layer
   unexpected_keys.remove('embed_out'				)
   lowerCAmelCase     =			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}'''				)

   lowerCAmelCase     =			SpeechEncoderDecoderModel(encoder=lowerCamelCase	, decoder=lowerCamelCase				)
   lowerCAmelCase     =			False

   # add projection layer
   lowerCAmelCase     =			nn.Parameter(projection_layer.weight				)
   lowerCAmelCase     =			nn.Parameter(projection_layer.bias				)

   lowerCAmelCase     =			create_vocab_dict(lowerCamelCase				)

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

   lowerCAmelCase     =			SpeechaTextaTokenizer(os.path.join(lowerCamelCase	, 'vocab.json'				)				)
   tokenizer.save_pretrained(lowerCamelCase				)

   lowerCAmelCase     =			hf_wavavec.config.to_dict()
   lowerCAmelCase     =			tokenizer.pad_token_id
   lowerCAmelCase     =			tokenizer.bos_token_id
   lowerCAmelCase     =			tokenizer.eos_token_id
   lowerCAmelCase     =			'speech_to_text_2'
   lowerCAmelCase     =			'wav2vec2'

   lowerCAmelCase     =			SpeechEncoderDecoderConfig.from_dict(lowerCamelCase				)

   hf_wavavec.save_pretrained(lowerCamelCase				)
   feature_extractor.save_pretrained(lowerCamelCase				)


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

       __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,
       )












import argparse
import copy



def _a				(	lowerCamelCase:   List[Any] )	->						List[str]:







      '''simple docstring'''






      __A          =				{}

      with open(lowerCamelCase ) as f:
            for line in f:
                  if line.split()[0] not in dict_of_neighbours:
                        __A          =				[]
                        _list.append([line.split()[1], line.split()[2]] )
                        __A          =				_list
                  else:
                        dict_of_neighbours[line.split()[0]].append(
                            [line.split()[1], line.split()[2]] )
                  if line.split()[1] not in dict_of_neighbours:
                        __A          =				[]
                        _list.append([line.split()[0], line.split()[2]] )
                        __A          =				_list
                  else:
                        dict_of_neighbours[line.split()[1]].append(
                            [line.split()[0], line.split()[2]] )

      return dict_of_neighbours



def _a				(	lowerCamelCase:   Any					,				lowerCamelCase:   Optional[Any] )	->						Dict:







      '''simple docstring'''






      with open(lowerCamelCase ) as f:
            __A          =				f.read(1 )
      __A          =				start_node

      __A          =				[]

      __A          =				start_node

      __A          =				0
      while visiting not in first_solution:
            __A          =				1_00_00
            for k in dict_of_neighbours[visiting]:
                  if int(k[1] ) < int(lowerCamelCase ) and k[0] not in first_solution:
                        __A          =				k[1]
                        __A          =				k[0]

            first_solution.append(lowerCamelCase )
            __A          =				distance_of_first_solution + int(lowerCamelCase )
            __A          =				best_node

      first_solution.append(lowerCamelCase )

      __A          =				0
      for k in dict_of_neighbours[first_solution[-2]]:
            if k[0] == start_node:
                  break
            position += 1

      __A          =				(
          distance_of_first_solution
          + int(dict_of_neighbours[first_solution[-2]][position][1] )
          - 1_00_00
      )
      return first_solution, distance_of_first_solution



def _a				(	lowerCamelCase:   List[str]					,				lowerCamelCase:   Any )	->						Any:







      '''simple docstring'''






      __A          =				[]

      for n in solution[1:-1]:
            __A          =				solution.index(lowerCamelCase )
            for kn in solution[1:-1]:
                  __A          =				solution.index(lowerCamelCase )
                  if n == kn:
                        continue

                  __A          =				copy.deepcopy(lowerCamelCase )
                  __A          =				kn
                  __A          =				n

                  __A          =				0

                  for k in _tmp[:-1]:
                        __A          =				_tmp[_tmp.index(lowerCamelCase ) + 1]
                        for i in dict_of_neighbours[k]:
                              if i[0] == next_node:
                                    __A          =				distance + int(i[1] )
                  _tmp.append(lowerCamelCase )

                  if _tmp not in neighborhood_of_solution:
                        neighborhood_of_solution.append(_tmp )

      __A          =				len(neighborhood_of_solution[0] ) - 1

      neighborhood_of_solution.sort(key=lambda lowerCamelCase : x[index_of_last_item_in_the_list] )
      return neighborhood_of_solution



def _a				(	lowerCamelCase:   Optional[int]					,				lowerCamelCase:   Dict					,				lowerCamelCase:   Any					,				lowerCamelCase:   Optional[int]					,				lowerCamelCase:   Union[str, Any] )	->						Any:







      '''simple docstring'''






      __A          =				1
      __A          =				first_solution
      __A          =				[]
      __A          =				distance_of_first_solution
      __A          =				solution

      while count <= iters:
            __A          =				find_neighborhood(lowerCamelCase					,				lowerCamelCase )
            __A          =				0
            __A          =				neighborhood[index_of_best_solution]
            __A          =				len(lowerCamelCase ) - 1

            __A          =				False
            while not found:
                  __A          =				0
                  while i < len(lowerCamelCase ):
                        if best_solution[i] != solution[i]:
                              __A          =				best_solution[i]
                              __A          =				solution[i]
                              break
                        __A          =				i + 1

                  if [first_exchange_node, second_exchange_node] not in tabu_list and [
                      second_exchange_node,
                      first_exchange_node,
                  ] not in tabu_list:
                        tabu_list.append([first_exchange_node, second_exchange_node] )
                        __A          =				True
                        __A          =				best_solution[:-1]
                        __A          =				neighborhood[index_of_best_solution][best_cost_index]
                        if cost < best_cost:
                              __A          =				cost
                              __A          =				solution
                  else:
                        __A          =				index_of_best_solution + 1
                        __A          =				neighborhood[index_of_best_solution]

            if len(lowerCamelCase ) >= size:
                  tabu_list.pop(0 )

            __A          =				count + 1

      return best_solution_ever, best_cost



def _a				(	lowerCamelCase:   List[str]=None )	->						str:







      '''simple docstring'''






      __A          =				generate_neighbours(args.File )

      __A   ,						__A          =				generate_first_solution(
          args.File					,				lowerCamelCase )

      __A   ,						__A          =				tabu_search(
          lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase					,				args.Iterations					,				args.Size					,				)

      print(F"""Best solution: {best_sol}, with total distance: {best_cost}.""" )


if __name__ == "__main__":
       snake_case__					:							Tuple													=     argparse.ArgumentParser(description='Tabu Search')
       parser.add_argument(
           '-f',
           '--File',
           type=str,
           help='Path to the file containing the data',
           required=True,
       )
       parser.add_argument(
           '-i',
           '--Iterations',
           type=int,
           help='How many iterations the algorithm should perform',
           required=True,
       )
       parser.add_argument(
           '-s', '--Size', type=int, help='Size of the tabu list', required=True
       )

       # Pass the arguments to main method
       main(parser.parse_args())





