timestamp_tools.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. import torch
  2. import copy
  3. import logging
  4. import numpy as np
  5. from typing import Any, List, Tuple, Union
  6. def cut_interval(alphas: torch.Tensor, start: int, end: int, tail: bool):
  7. if not tail:
  8. if end == start + 1:
  9. cut = (end + start) / 2.0
  10. else:
  11. alpha = alphas[start+1: end].tolist()
  12. reverse_steps = 1
  13. for reverse_alpha in alpha[::-1]:
  14. if reverse_alpha > 0.35:
  15. reverse_steps += 1
  16. else:
  17. break
  18. cut = end - reverse_steps
  19. else:
  20. if end != len(alphas) - 1:
  21. cut = end + 1
  22. else:
  23. cut = start + 1
  24. return float(cut)
  25. def time_stamp_lfr6(alphas: torch.Tensor, speech_lengths: torch.Tensor, raw_text: List[str], begin: int = 0, end: int = None):
  26. time_stamp_list = []
  27. alphas = alphas[0]
  28. text = copy.deepcopy(raw_text)
  29. if end is None:
  30. time = speech_lengths * 60 / 1000
  31. sacle_rate = (time / speech_lengths[0]).tolist()
  32. else:
  33. time = (end - begin) / 1000
  34. sacle_rate = (time / speech_lengths[0]).tolist()
  35. predictor = (alphas > 0.5).int()
  36. fire_places = torch.nonzero(predictor == 1).squeeze(1).tolist()
  37. cuts = []
  38. npeak = int(predictor.sum())
  39. nchar = len(raw_text)
  40. if npeak - 1 == nchar:
  41. fire_places = torch.where((alphas > 0.5) == 1)[0].tolist()
  42. for i in range(len(fire_places)):
  43. if fire_places[i] < len(alphas) - 1:
  44. if 0.05 < alphas[fire_places[i]+1] < 0.5:
  45. fire_places[i] += 1
  46. elif npeak < nchar:
  47. lost_num = nchar - npeak
  48. lost_fire = speech_lengths[0].tolist() - fire_places[-1]
  49. interval_distance = lost_fire // (lost_num + 1)
  50. for i in range(1, lost_num + 1):
  51. fire_places.append(fire_places[-1] + interval_distance)
  52. elif npeak - 1 > nchar:
  53. redundance_num = npeak - 1 - nchar
  54. for i in range(redundance_num):
  55. fire_places.pop()
  56. cuts.append(0)
  57. start_sil = True
  58. if start_sil:
  59. text.insert(0, '<sil>')
  60. for i in range(len(fire_places)-1):
  61. cuts.append(cut_interval(alphas, fire_places[i], fire_places[i+1], tail=(i==len(fire_places)-2)))
  62. for i in range(2, len(fire_places)-2):
  63. if fire_places[i-2] == fire_places[i-1] - 1 and fire_places[i-1] != fire_places[i] - 1:
  64. cuts[i-1] += 1
  65. if cuts[-1] != len(alphas) - 1:
  66. text.append('<sil>')
  67. cuts.append(speech_lengths[0].tolist())
  68. cuts.insert(-1, (cuts[-1] + cuts[-2]) * 0.5)
  69. sec_fire_places = np.array(cuts) * sacle_rate
  70. for i in range(1, len(sec_fire_places) - 1):
  71. start, end = sec_fire_places[i], sec_fire_places[i+1]
  72. if i == len(sec_fire_places) - 2:
  73. end = time
  74. time_stamp_list.append([int(round(start, 2) * 1000) + begin, int(round(end, 2) * 1000) + begin])
  75. text = text[1:]
  76. if npeak - 1 == nchar or npeak > nchar:
  77. return time_stamp_list[:-1]
  78. else:
  79. return time_stamp_list
  80. def time_stamp_lfr6_pl(us_alphas, us_cif_peak, char_list, begin_time=0.0, end_time=None):
  81. START_END_THRESHOLD = 5
  82. TIME_RATE = 10.0 * 6 / 1000 / 3 # 3 times upsampled
  83. if len(us_alphas.shape) == 3:
  84. alphas, cif_peak = us_alphas[0], us_cif_peak[0] # support inference batch_size=1 only
  85. else:
  86. alphas, cif_peak = us_alphas, us_cif_peak
  87. num_frames = cif_peak.shape[0]
  88. if char_list[-1] == '</s>':
  89. char_list = char_list[:-1]
  90. # char_list = [i for i in text]
  91. timestamp_list = []
  92. # for bicif model trained with large data, cif2 actually fires when a character starts
  93. # so treat the frames between two peaks as the duration of the former token
  94. fire_place = torch.where(cif_peak>1.0-1e-4)[0].cpu().numpy() - 1.5
  95. num_peak = len(fire_place)
  96. assert num_peak == len(char_list) + 1 # number of peaks is supposed to be number of tokens + 1
  97. # begin silence
  98. if fire_place[0] > START_END_THRESHOLD:
  99. char_list.insert(0, '<sil>')
  100. timestamp_list.append([0.0, fire_place[0]*TIME_RATE])
  101. # tokens timestamp
  102. for i in range(len(fire_place)-1):
  103. # the peak is always a little ahead of the start time
  104. # timestamp_list.append([(fire_place[i]-1.2)*TIME_RATE, fire_place[i+1]*TIME_RATE])
  105. timestamp_list.append([(fire_place[i])*TIME_RATE, fire_place[i+1]*TIME_RATE])
  106. # cut the duration to token and sil of the 0-weight frames last long
  107. # tail token and end silence
  108. if num_frames - fire_place[-1] > START_END_THRESHOLD:
  109. _end = (num_frames + fire_place[-1]) / 2
  110. timestamp_list[-1][1] = _end*TIME_RATE
  111. timestamp_list.append([_end*TIME_RATE, num_frames*TIME_RATE])
  112. char_list.append("<sil>")
  113. else:
  114. timestamp_list[-1][1] = num_frames*TIME_RATE
  115. if begin_time: # add offset time in model with vad
  116. for i in range(len(timestamp_list)):
  117. timestamp_list[i][0] = timestamp_list[i][0] + begin_time / 1000.0
  118. timestamp_list[i][1] = timestamp_list[i][1] + begin_time / 1000.0
  119. res_txt = ""
  120. for char, timestamp in zip(char_list, timestamp_list):
  121. res_txt += "{} {} {};".format(char, timestamp[0], timestamp[1])
  122. logging.warning(res_txt) # for test
  123. res = []
  124. for char, timestamp in zip(char_list, timestamp_list):
  125. if char != '<sil>':
  126. res.append([int(timestamp[0] * 1000), int(timestamp[1] * 1000)])
  127. return res