'''simple docstring'''




import argparse
import os
from dataclasses import dataclass

import torch
import torchaudio
from tqdm import tqdm

from transformers import AutoConfig, AutoModelForCTC, AutoProcessor




class 					a__   :






     def __init__(				self	:	Optional[Any]						,       a	:	int						,       a	:	Optional[Any]						,       a	:	Dict					):





         """simple docstring"""



         __lowerCamelCase						=						cuda
         __lowerCamelCase						=						AutoConfig.from_pretrained(a					)
         __lowerCamelCase						=						AutoModelForCTC.from_pretrained(a					)
         self.model.eval()
         if self.cuda:
             self.model.to(device='''cuda'''					)
         __lowerCamelCase						=						AutoProcessor.from_pretrained(a					)
         __lowerCamelCase						=						torchaudio.transforms.Resample(a						,       1_60_00					)
         __lowerCamelCase						=						0
         __lowerCamelCase						=						list(self.processor.tokenizer.get_vocab().keys()					)
         for i in range(len(a					)					):
             if vocab[i] == "[PAD]" or vocab[i] == "<pad>":
                 __lowerCamelCase						=						i
         print('''Blank Token id [PAD]/<pad>'''						,       a					)
         __lowerCamelCase						=						blank_id






     def      SCREAMING_SNAKE_CASE__     (				self	:	Tuple						,       a	:	Tuple					):





         """simple docstring"""



         __lowerCamelCase			,						__lowerCamelCase						=						torchaudio.load(a					)
         __lowerCamelCase						=						self.resampler(a					).squeeze().numpy()
         return speech






     def      SCREAMING_SNAKE_CASE__     (				self	:	Dict						,       a	:	Any					):





         """simple docstring"""



         __lowerCamelCase						=						self.blank_id
         __lowerCamelCase						=						'''|'''.join(item['''sent'''].split(''' '''					)					)
         if not os.path.isfile(item['''wav_path''']					):
             print(item['''wav_path''']						,       '''not found in wavs directory'''					)

         __lowerCamelCase						=						self.speech_file_to_array_fn(item['''wav_path''']					)
         __lowerCamelCase						=						self.processor(a						,       sampling_rate=1_60_00						,       return_tensors='''pt'''						,       padding=a					)
         if self.cuda:
             __lowerCamelCase						=						inputs.to(device='''cuda'''					)

         with torch.no_grad():
             __lowerCamelCase						=						self.model(inputs.input_values					).logits

         # get the emission probability at frame level
         __lowerCamelCase						=						torch.log_softmax(a						,       dim=-1					)
         __lowerCamelCase						=						emissions[0].cpu().detach()

         # get labels from vocab
         __lowerCamelCase						=						([''''''] + list(self.processor.tokenizer.get_vocab().keys()					))[
             :-1
         ]  # logits don't align with the tokenizer's vocab

         __lowerCamelCase						=						{c: i for i, c in enumerate(a					)}
         __lowerCamelCase						=						[]
         for c in transcript:
             if c in dictionary:
                 tokens.append(dictionary[c]					)

         def get_trellis(a	:	Dict						,       a	:	Union[str, Any]						,       a	:	List[str]=0					):
             __lowerCamelCase						=						emission.size(0					)
             __lowerCamelCase						=						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.
             __lowerCamelCase						=						torch.full((num_frames + 1, num_tokens + 1)						,       -float('''inf'''					)					)
             __lowerCamelCase						=						0
             for t in range(a					):
                 __lowerCamelCase						=						torch.maximum(
                     # Score for staying at the same token
                     trellis[t, 1:] + emission[t, blank_id]						,       trellis[t, :-1] + emission[t, tokens]						,       )
             return trellis

         __lowerCamelCase						=						get_trellis(a						,       a						,       a					)




         @dataclass
         class 					a__   :
              lowerCamelCase						:  int
              lowerCamelCase						:  int
              lowerCamelCase						:  float

         def backtrack(a	:	str						,       a	:	Optional[int]						,       a	:	int						,       a	:	List[Any]=0					):
             __lowerCamelCase						=						trellis.size(1					) - 1
             __lowerCamelCase						=						torch.argmax(trellis[:, j]					).item()

             __lowerCamelCase						=						[]
             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.
                 __lowerCamelCase						=						trellis[t - 1, j] + emission[t - 1, blank_id]
                 # Score for token changing from C-1 at T-1 to J at T.
                 __lowerCamelCase						=						trellis[t - 1, j - 1] + emission[t - 1, tokens[j - 1]]

                 # 2. Store the path with frame-wise probability.
                 __lowerCamelCase						=						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]

         __lowerCamelCase						=						backtrack(a						,       a						,       a						,       a					)




         @dataclass
         class 					a__   :
              lowerCamelCase						:  str
              lowerCamelCase						:  int
              lowerCamelCase						:  int
              lowerCamelCase						:  float






              def __repr__(				self	:	List[str]					):





                  """simple docstring"""



                  return f"""{self.label}\t{self.score:4.2f}\t{self.start*20:5d}\t{self.end*20:5d}"""






              @property
              def      SCREAMING_SNAKE_CASE__     (				self	:	Union[str, Any]					):





                  """simple docstring"""



                  return self.end - self.start

         def merge_repeats(a	:	Dict					):
             __lowerCamelCase			,						__lowerCamelCase						=						0, 0
             __lowerCamelCase						=						[]
             while ia < len(a					):
                 while ia < len(a					) and path[ia].token_index == path[ia].token_index:
                     ia += 1
                 __lowerCamelCase						=						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						,       )					)
                 __lowerCamelCase						=						ia
             return segments

         __lowerCamelCase						=						merge_repeats(a					)
         with open(item['''out_path''']						,       '''w'''					) as out_align:
             for seg in segments:
                 out_align.write(str(a					) + '''\n'''					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	Tuple						,       a	:	int						,       a	:	Union[str, Any]						,       a	:	Union[str, Any]					):





         """simple docstring"""



         if not os.path.exists(a					):
             os.makedirs(a					)

         # load text file
         __lowerCamelCase						=						open(a						,       encoding='''utf8'''					).readlines()

         __lowerCamelCase						=						[]
         for line in lines:
             if len(line.strip().split('''\t'''					)					) != 2:
                 print('''Script must be in format: 00001  this is my sentence'''					)
                 exit()

             __lowerCamelCase			,						__lowerCamelCase						=						line.strip().split('''\t'''					)
             __lowerCamelCase						=						os.path.join(a						,       wav_name + '''.wav'''					)
             __lowerCamelCase						=						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 __lowerCAmelCase				(							)			->					List[str]:
    __lowerCamelCase						=						argparse.ArgumentParser()

    parser.add_argument(
        '''--model_name'''       ,						type=UpperCamelCase__       ,						default='''arijitx/wav2vec2-xls-r-300m-bengali'''       ,						help='''wav2vec model name'''       )
    parser.add_argument('''--wav_dir'''       ,						type=UpperCamelCase__       ,						default='''./wavs'''       ,						help='''directory containing wavs'''       )
    parser.add_argument('''--text_file'''       ,						type=UpperCamelCase__       ,						default='''script.txt'''       ,						help='''file containing text'''       )
    parser.add_argument('''--input_wavs_sr'''       ,						type=UpperCamelCase__       ,						default=1_60_00       ,						help='''sampling rate of input audios'''       )
    parser.add_argument(
        '''--output_dir'''       ,						type=UpperCamelCase__       ,						default='''./out_alignment'''       ,						help='''output directory containing the alignment files'''       )
    parser.add_argument('''--cuda'''       ,						action='''store_true'''       )

    __lowerCamelCase						=						parser.parse_args()

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

'''simple docstring'''




__UpperCAmelCase  							=1_0**8






def __lowerCAmelCase				(							UpperCamelCase__       )			->					bool:
    if n % 10 == 0:
        return False
    __lowerCamelCase						=						str(UpperCamelCase__       )
    return s == s[::-1]






def __lowerCAmelCase				(							)			->					int:
    __lowerCamelCase						=						set()
    __lowerCamelCase						=						1
    __lowerCamelCase						=						5
    while sum_squares < LIMIT:
        __lowerCamelCase						=						first_square + 1
        while sum_squares < LIMIT:
            if is_palindrome(UpperCamelCase__       ):
                answer.add(UpperCamelCase__       )
            last_square += 1
            sum_squares += last_square**2
        first_square += 1
        __lowerCamelCase						=						first_square**2 + (first_square + 1) ** 2

    return sum(UpperCamelCase__       )


if __name__ == "__main__":
  print(solution())
