timestamp_tools.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import torch
  2. import copy
  3. import logging
  4. import numpy as np
  5. from typing import Any, List, Tuple, Union
  6. def time_stamp_lfr6_pl(us_alphas, us_cif_peak, char_list, begin_time=0.0, end_time=None):
  7. START_END_THRESHOLD = 5
  8. TIME_RATE = 10.0 * 6 / 1000 / 3 # 3 times upsampled
  9. if len(us_alphas.shape) == 3:
  10. alphas, cif_peak = us_alphas[0], us_cif_peak[0] # support inference batch_size=1 only
  11. else:
  12. alphas, cif_peak = us_alphas, us_cif_peak
  13. num_frames = cif_peak.shape[0]
  14. if char_list[-1] == '</s>':
  15. char_list = char_list[:-1]
  16. # char_list = [i for i in text]
  17. timestamp_list = []
  18. # for bicif model trained with large data, cif2 actually fires when a character starts
  19. # so treat the frames between two peaks as the duration of the former token
  20. fire_place = torch.where(cif_peak>1.0-1e-4)[0].cpu().numpy() - 1.5
  21. num_peak = len(fire_place)
  22. assert num_peak == len(char_list) + 1 # number of peaks is supposed to be number of tokens + 1
  23. # begin silence
  24. if fire_place[0] > START_END_THRESHOLD:
  25. char_list.insert(0, '<sil>')
  26. timestamp_list.append([0.0, fire_place[0]*TIME_RATE])
  27. # tokens timestamp
  28. for i in range(len(fire_place)-1):
  29. # the peak is always a little ahead of the start time
  30. # timestamp_list.append([(fire_place[i]-1.2)*TIME_RATE, fire_place[i+1]*TIME_RATE])
  31. timestamp_list.append([(fire_place[i])*TIME_RATE, fire_place[i+1]*TIME_RATE])
  32. # cut the duration to token and sil of the 0-weight frames last long
  33. # tail token and end silence
  34. if num_frames - fire_place[-1] > START_END_THRESHOLD:
  35. _end = (num_frames + fire_place[-1]) / 2
  36. timestamp_list[-1][1] = _end*TIME_RATE
  37. timestamp_list.append([_end*TIME_RATE, num_frames*TIME_RATE])
  38. char_list.append("<sil>")
  39. else:
  40. timestamp_list[-1][1] = num_frames*TIME_RATE
  41. if begin_time: # add offset time in model with vad
  42. for i in range(len(timestamp_list)):
  43. timestamp_list[i][0] = timestamp_list[i][0] + begin_time / 1000.0
  44. timestamp_list[i][1] = timestamp_list[i][1] + begin_time / 1000.0
  45. res_txt = ""
  46. for char, timestamp in zip(char_list, timestamp_list):
  47. res_txt += "{} {} {};".format(char, timestamp[0], timestamp[1])
  48. res = []
  49. for char, timestamp in zip(char_list, timestamp_list):
  50. if char != '<sil>':
  51. res.append([int(timestamp[0] * 1000), int(timestamp[1] * 1000)])
  52. return res