timestamp_utils.py 2.7 KB

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