code: 
  
  
  import argparse
  import os
  from dataclasses import dataclass
  
  import torch
  import torchaudio
  from tqdm import tqdm
  
  from transformers import AutoConfig, AutoModelForCTC, AutoProcessor
  
  
  
  class   __lowerCamelCase :
  
  
  
  
  
  
  
         def __init__( self:   Optional[Any],A_:   List[str],A_:   Any,A_:   int				):
  
  
  
  
  
  
              '''simple docstring'''
  
  
  
  
              __UpperCamelCase   = cuda
              __UpperCamelCase   = AutoConfig.from_pretrained(A_				)
              __UpperCamelCase   = AutoModelForCTC.from_pretrained(A_				)
              self.model.eval()
              if self.cuda:
                   self.model.to(device='cuda'				)
              __UpperCamelCase   = AutoProcessor.from_pretrained(A_				)
              __UpperCamelCase   = torchaudio.transforms.Resample(A_,1_6000				)
              __UpperCamelCase   = 0
              __UpperCamelCase   = list(self.processor.tokenizer.get_vocab().keys()				)
              for i in range(len(A_				)				):
                   if vocab[i] == "[PAD]" or vocab[i] == "<pad>":
                        __UpperCamelCase   = i
              print('Blank Token id [PAD]/<pad>',A_				)
              __UpperCamelCase   = blank_id
  
  
  
  
  
  
  
         def 		snake_case_  ( self:   Optional[Any],A_:   List[str]				):
  
  
  
  
  
  
              '''simple docstring'''
  
  
  
  
              __UpperCamelCase,						__UpperCamelCase   = torchaudio.load(A_				)
              __UpperCamelCase   = self.resampler(A_				).squeeze().numpy()
              return speech
  
  
  
  
  
  
  
         def 		snake_case_  ( self:   Union[str, Any],A_:   List[str]				):
  
  
  
  
  
  
              '''simple docstring'''
  
  
  
  
              __UpperCamelCase   = self.blank_id
              __UpperCamelCase   = '|'.join(item['sent'].split(' '				)				)
              if not os.path.isfile(item['wav_path']				):
                   print(item['wav_path'],'not found in wavs directory'				)
  
              __UpperCamelCase   = self.speech_file_to_array_fn(item['wav_path']				)
              __UpperCamelCase   = self.processor(A_,sampling_rate=1_6000,return_tensors='pt',padding=A_				)
              if self.cuda:
                   __UpperCamelCase   = inputs.to(device='cuda'				)
  
              with torch.no_grad():
                   __UpperCamelCase   = self.model(inputs.input_values				).logits
  
              # get the emission probability at frame level
              __UpperCamelCase   = torch.log_softmax(A_,dim=-1				)
              __UpperCamelCase   = emissions[0].cpu().detach()
  
              # get labels from vocab
              __UpperCamelCase   = ([''] + list(self.processor.tokenizer.get_vocab().keys()				))[
                  :-1
              ]  # logits don't align with the tokenizer's vocab
  
              __UpperCamelCase   = {c: i for i, c in enumerate(A_				)}
              __UpperCamelCase   = []
              for c in transcript:
                   if c in dictionary:
                        tokens.append(dictionary[c]				)
  
              def get_trellis(A_:   int,A_:   Dict,A_:   Tuple=0				):
                   __UpperCamelCase   = emission.size(0				)
                   __UpperCamelCase   = len(A_				)
  
                   # Trellis has extra diemsions for both time axis and tokens.
                   # The extra dim for tokens represents <SoS> (start-of-sentence)
                   # The extra dim for time axis is for simplification of the code.
                   __UpperCamelCase   = torch.full((num_frames + 1, num_tokens + 1),-float('inf'				)				)
                   __UpperCamelCase   = 0
                   for t in range(A_				):
                        __UpperCamelCase   = torch.maximum(
                            # Score for staying at the same token
                            trellis[t, 1:] + emission[t, blank_id],trellis[t, :-1] + emission[t, tokens],)
                   return trellis
  
              __UpperCamelCase   = get_trellis(A_,A_,A_				)
  
  
  
              @dataclass
              class   __lowerCamelCase :
                     _lowercase       							=    42
                     _lowercase       							=    42
                     _lowercase       							=    42
  
              def backtrack(A_:   int,A_:   List[Any],A_:   Dict,A_:   int=0				):
                   __UpperCamelCase   = trellis.size(1				) - 1
                   __UpperCamelCase   = torch.argmax(trellis[:, j]				).item()
  
                   __UpperCamelCase   = []
                   for t in range(A_,0,-1				):
                        # 1. Figure out if the current position was stay or change
                        # Note (again):
                        # `emission[J-1]` is the emission at time frame `J` of trellis dimension.
                        # Score for token staying the same from time frame J-1 to T.
                        __UpperCamelCase   = trellis[t - 1, j] + emission[t - 1, blank_id]
                        # Score for token changing from C-1 at T-1 to J at T.
                        __UpperCamelCase   = trellis[t - 1, j - 1] + emission[t - 1, tokens[j - 1]]
  
                        # 2. Store the path with frame-wise probability.
                        __UpperCamelCase   = emission[t - 1, tokens[j - 1] if changed > stayed else 0].exp().item()
                        # Return token index and time index in non-trellis coordinate.
                        path.append(Point(j - 1,t - 1,A_				)				)
  
                        # 3. Update the token
                        if changed > stayed:
                             j -= 1
                             if j == 0:
                                  break
                   else:
                        raise ValueError('Failed to align'				)
                   return path[::-1]
  
              __UpperCamelCase   = backtrack(A_,A_,A_,A_				)
  
  
  
              @dataclass
              class   __lowerCamelCase :
                     _lowercase       							=    42
                     _lowercase       							=    42
                     _lowercase       							=    42
                     _lowercase       							=    42
  
  
  
  
  
  
  
                     def __repr__( self:   Tuple				):
  
  
  
  
  
  
                          '''simple docstring'''
  
  
  
  
                          return F'''{self.label}\t{self.score:4.2f}\t{self.start*20:5d}\t{self.end*20:5d}'''
  
  
  
  
  
  
  
                     @property
                     def 		snake_case_  ( self:   Optional[int]				):
  
  
  
  
  
  
                          '''simple docstring'''
  
  
  
  
                          return self.end - self.start
  
              def merge_repeats(A_:   Union[str, Any]				):
                   __UpperCamelCase,						__UpperCamelCase   = 0, 0
                   __UpperCamelCase   = []
                   while ia < len(A_				):
                        while ia < len(A_				) and path[ia].token_index == path[ia].token_index:
                             ia += 1
                        __UpperCamelCase   = sum(path[k].score for k in range(A_,A_				)				) / (ia - ia)
                        segments.append(
                            Segment(
                                transcript[path[ia].token_index],path[ia].time_index,path[ia - 1].time_index + 1,A_,)				)
                        __UpperCamelCase   = ia
                   return segments
  
              __UpperCamelCase   = merge_repeats(A_				)
              with open(item['out_path'],'w'				) as out_align:
                   for seg in segments:
                        out_align.write(str(A_				) + '\n'				)
  
  
  
  
  
  
  
         def 		snake_case_  ( self:   Dict,A_:   Union[str, Any],A_:   List[Any],A_:   Tuple				):
  
  
  
  
  
  
              '''simple docstring'''
  
  
  
  
              if not os.path.exists(A_				):
                   os.makedirs(A_				)
  
              # load text file
              __UpperCamelCase   = open(A_,encoding='utf8'				).readlines()
  
              __UpperCamelCase   = []
              for line in lines:
                   if len(line.strip().split('\t'				)				) != 2:
                        print('Script must be in format: 00001  this is my sentence'				)
                        exit()
  
                   __UpperCamelCase,						__UpperCamelCase   = line.strip().split('\t'				)
                   __UpperCamelCase   = os.path.join(A_,wav_name + '.wav'				)
                   __UpperCamelCase   = os.path.join(A_,wav_name + '.txt'				)
  
                   items.append({'sent': sentence, 'wav_path': wav_path, 'out_path': out_path}				)
              print('Number of samples found in script file',len(A_				)				)
  
              for item in tqdm(A_				):
                   self.align_single_sample(A_				)
  
  
  
  
  
  
  def 		_A		(		)				->   List[Any]:
  
  
       """simple docstring"""
  
  
       __UpperCamelCase   = argparse.ArgumentParser()
  
       parser.add_argument(
           '--model_name'				,     type=_lowercase				,     default='arijitx/wav2vec2-xls-r-300m-bengali'				,     help='wav2vec model name'   )
       parser.add_argument('--wav_dir'				,     type=_lowercase				,     default='./wavs'				,     help='directory containing wavs'   )
       parser.add_argument('--text_file'				,     type=_lowercase				,     default='script.txt'				,     help='file containing text'   )
       parser.add_argument('--input_wavs_sr'				,     type=_lowercase				,     default=1_60_00				,     help='sampling rate of input audios'   )
       parser.add_argument(
           '--output_dir'				,     type=_lowercase				,     default='./out_alignment'				,     help='output directory containing the alignment files'   )
       parser.add_argument('--cuda'				,     action='store_true'   )
  
       __UpperCamelCase   = parser.parse_args()
  
       __UpperCamelCase   = WavaVecaAligner(args.model_name				,     args.input_wavs_sr				,     args.cuda   )
       aligner.align_data(args.wav_dir				,     args.text_file				,     args.output_dir   )
  
  
  if __name__ == "__main__":
      main()
  
  
  
style_context: 
  
  
  import argparse
  import json
  
  from transformers import GPTNeoConfig, GPTNeoForCausalLM, load_tf_weights_in_gpt_neo
  from transformers.utils import logging
  
  
  logging.set_verbosity_info()
  
  
  
  
  
  
  def 		_A		(		_lowercase				,     _lowercase				,     _lowercase   )				->   List[str]:
  
  
       """simple docstring"""
  
  
       __UpperCamelCase   = json.load(open(_lowercase				,     'r'   )   )
       __UpperCamelCase   = GPTNeoConfig(
           hidden_size=config_json['n_embd']				,     num_layers=config_json['n_layer']				,     num_heads=config_json['n_head']				,     attention_types=config_json['attention_types']				,     max_position_embeddings=config_json['n_positions']				,     resid_dropout=config_json['res_dropout']				,     embed_dropout=config_json['embed_dropout']				,     attention_dropout=config_json['attn_dropout']				,     )
       print(f'''Building PyTorch model from configuration: {config}'''   )
       __UpperCamelCase   = GPTNeoForCausalLM(_lowercase   )
  
       # Load weights from tf checkpoint
       load_tf_weights_in_gpt_neo(_lowercase				,     _lowercase				,     _lowercase   )
  
       # Save pytorch-model
       print(f'''Save PyTorch model to {pytorch_dump_path}'''   )
       model.save_pretrained(_lowercase   )
  
  
  if __name__ == "__main__":
      __snake_case             =	argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.'''
      )
      parser.add_argument(
          '''--config_file''',
          default=None,
          type=str,
          required=True,
          help=(
              '''The config json file corresponding to the pre-trained mesh-tf model. \n'''
              '''This specifies the model architecture.'''
          ),
      )
      parser.add_argument(
          '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
      )
      __snake_case             =	parser.parse_args()
      convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
  
  
  