timestamp_tools.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. from itertools import zip_longest
  2. import torch
  3. import copy
  4. import codecs
  5. import logging
  6. import edit_distance
  7. import argparse
  8. import pdb
  9. import numpy as np
  10. from typing import Any, List, Tuple, Union
  11. def ts_prediction_lfr6_standard(us_alphas,
  12. us_peaks,
  13. char_list,
  14. vad_offset=0.0,
  15. force_time_shift=-1.5,
  16. sil_in_str=True
  17. ):
  18. if not len(char_list):
  19. return "", []
  20. START_END_THRESHOLD = 5
  21. MAX_TOKEN_DURATION = 12
  22. TIME_RATE = 10.0 * 6 / 1000 / 3 # 3 times upsampled
  23. if len(us_alphas.shape) == 2:
  24. _, peaks = us_alphas[0], us_peaks[0] # support inference batch_size=1 only
  25. else:
  26. _, peaks = us_alphas, us_peaks
  27. num_frames = peaks.shape[0]
  28. if char_list[-1] == '</s>':
  29. char_list = char_list[:-1]
  30. timestamp_list = []
  31. new_char_list = []
  32. # for bicif model trained with large data, cif2 actually fires when a character starts
  33. # so treat the frames between two peaks as the duration of the former token
  34. fire_place = torch.where(peaks>1.0-1e-4)[0].cpu().numpy() + force_time_shift # total offset
  35. num_peak = len(fire_place)
  36. assert num_peak == len(char_list) + 1 # number of peaks is supposed to be number of tokens + 1
  37. # begin silence
  38. if fire_place[0] > START_END_THRESHOLD:
  39. # char_list.insert(0, '<sil>')
  40. timestamp_list.append([0.0, fire_place[0]*TIME_RATE])
  41. new_char_list.append('<sil>')
  42. # tokens timestamp
  43. for i in range(len(fire_place)-1):
  44. new_char_list.append(char_list[i])
  45. if MAX_TOKEN_DURATION < 0 or fire_place[i+1] - fire_place[i] <= MAX_TOKEN_DURATION:
  46. timestamp_list.append([fire_place[i]*TIME_RATE, fire_place[i+1]*TIME_RATE])
  47. else:
  48. # cut the duration to token and sil of the 0-weight frames last long
  49. _split = fire_place[i] + MAX_TOKEN_DURATION
  50. timestamp_list.append([fire_place[i]*TIME_RATE, _split*TIME_RATE])
  51. timestamp_list.append([_split*TIME_RATE, fire_place[i+1]*TIME_RATE])
  52. new_char_list.append('<sil>')
  53. # tail token and end silence
  54. # new_char_list.append(char_list[-1])
  55. if num_frames - fire_place[-1] > START_END_THRESHOLD:
  56. _end = (num_frames + fire_place[-1]) * 0.5
  57. # _end = fire_place[-1]
  58. timestamp_list[-1][1] = _end*TIME_RATE
  59. timestamp_list.append([_end*TIME_RATE, num_frames*TIME_RATE])
  60. new_char_list.append("<sil>")
  61. else:
  62. timestamp_list[-1][1] = num_frames*TIME_RATE
  63. if vad_offset: # add offset time in model with vad
  64. for i in range(len(timestamp_list)):
  65. timestamp_list[i][0] = timestamp_list[i][0] + vad_offset / 1000.0
  66. timestamp_list[i][1] = timestamp_list[i][1] + vad_offset / 1000.0
  67. res_txt = ""
  68. for char, timestamp in zip(new_char_list, timestamp_list):
  69. #if char != '<sil>':
  70. if not sil_in_str and char == '<sil>': continue
  71. res_txt += "{} {} {};".format(char, str(timestamp[0]+0.0005)[:5], str(timestamp[1]+0.0005)[:5])
  72. res = []
  73. for char, timestamp in zip(new_char_list, timestamp_list):
  74. if char != '<sil>':
  75. res.append([int(timestamp[0] * 1000), int(timestamp[1] * 1000)])
  76. return res_txt, res
  77. def time_stamp_sentence(punc_id_list, time_stamp_postprocessed, text_postprocessed):
  78. punc_list = [',', '。', '?', '、']
  79. res = []
  80. if text_postprocessed is None:
  81. return res
  82. if time_stamp_postprocessed is None:
  83. return res
  84. if len(time_stamp_postprocessed) == 0:
  85. return res
  86. if len(text_postprocessed) == 0:
  87. return res
  88. if punc_id_list is None or len(punc_id_list) == 0:
  89. res.append({
  90. 'text': text_postprocessed.split(),
  91. "start": time_stamp_postprocessed[0][0],
  92. "end": time_stamp_postprocessed[-1][1],
  93. 'text_seg': text_postprocessed.split(),
  94. "ts_list": time_stamp_postprocessed,
  95. })
  96. return res
  97. if len(punc_id_list) != len(time_stamp_postprocessed):
  98. print(" warning length mistach!!!!!!")
  99. sentence_text = ""
  100. sentence_text_seg = ""
  101. ts_list = []
  102. sentence_start = time_stamp_postprocessed[0][0]
  103. sentence_end = time_stamp_postprocessed[0][1]
  104. texts = text_postprocessed.split()
  105. punc_stamp_text_list = list(zip_longest(punc_id_list, time_stamp_postprocessed, texts, fillvalue=None))
  106. for punc_stamp_text in punc_stamp_text_list:
  107. punc_id, time_stamp, text = punc_stamp_text
  108. # sentence_text += text if text is not None else ''
  109. if text is not None:
  110. if 'a' <= text[0] <= 'z' or 'A' <= text[0] <= 'Z':
  111. sentence_text += ' ' + text
  112. elif len(sentence_text) and ('a' <= sentence_text[-1] <= 'z' or 'A' <= sentence_text[-1] <= 'Z'):
  113. sentence_text += ' ' + text
  114. else:
  115. sentence_text += text
  116. sentence_text_seg += text + ' '
  117. ts_list.append(time_stamp)
  118. punc_id = int(punc_id) if punc_id is not None else 1
  119. sentence_end = time_stamp[1] if time_stamp is not None else sentence_end
  120. if punc_id > 1:
  121. sentence_text += punc_list[punc_id - 2]
  122. res.append({
  123. 'text': sentence_text,
  124. "start": sentence_start,
  125. "end": sentence_end,
  126. "text_seg": sentence_text_seg,
  127. "ts_list": ts_list
  128. })
  129. sentence_text = ''
  130. sentence_text_seg = ''
  131. ts_list = []
  132. sentence_start = sentence_end
  133. return res
  134. class AverageShiftCalculator():
  135. def __init__(self):
  136. logging.warning("Calculating average shift.")
  137. def __call__(self, file1, file2):
  138. uttid_list1, ts_dict1 = self.read_timestamps(file1)
  139. uttid_list2, ts_dict2 = self.read_timestamps(file2)
  140. uttid_intersection = self._intersection(uttid_list1, uttid_list2)
  141. res = self.as_cal(uttid_intersection, ts_dict1, ts_dict2)
  142. logging.warning("Average shift of {} and {}: {}.".format(file1, file2, str(res)[:8]))
  143. logging.warning("Following timestamp pair differs most: {}, detail:{}".format(self.max_shift, self.max_shift_uttid))
  144. def _intersection(self, list1, list2):
  145. set1 = set(list1)
  146. set2 = set(list2)
  147. if set1 == set2:
  148. logging.warning("Uttid same checked.")
  149. return set1
  150. itsc = list(set1 & set2)
  151. logging.warning("Uttid differs: file1 {}, file2 {}, lines same {}.".format(len(list1), len(list2), len(itsc)))
  152. return itsc
  153. def read_timestamps(self, file):
  154. # read timestamps file in standard format
  155. uttid_list = []
  156. ts_dict = {}
  157. with codecs.open(file, 'r') as fin:
  158. for line in fin.readlines():
  159. text = ''
  160. ts_list = []
  161. line = line.rstrip()
  162. uttid = line.split()[0]
  163. uttid_list.append(uttid)
  164. body = " ".join(line.split()[1:])
  165. for pd in body.split(';'):
  166. if not len(pd): continue
  167. # pdb.set_trace()
  168. char, start, end = pd.lstrip(" ").split(' ')
  169. text += char + ','
  170. ts_list.append((float(start), float(end)))
  171. # ts_lists.append(ts_list)
  172. ts_dict[uttid] = (text[:-1], ts_list)
  173. logging.warning("File {} read done.".format(file))
  174. return uttid_list, ts_dict
  175. def _shift(self, filtered_timestamp_list1, filtered_timestamp_list2):
  176. shift_time = 0
  177. for fts1, fts2 in zip(filtered_timestamp_list1, filtered_timestamp_list2):
  178. shift_time += abs(fts1[0] - fts2[0]) + abs(fts1[1] - fts2[1])
  179. num_tokens = len(filtered_timestamp_list1)
  180. return shift_time, num_tokens
  181. def as_cal(self, uttid_list, ts_dict1, ts_dict2):
  182. # calculate average shift between timestamp1 and timestamp2
  183. # when characters differ, use edit distance alignment
  184. # and calculate the error between the same characters
  185. self._accumlated_shift = 0
  186. self._accumlated_tokens = 0
  187. self.max_shift = 0
  188. self.max_shift_uttid = None
  189. for uttid in uttid_list:
  190. (t1, ts1) = ts_dict1[uttid]
  191. (t2, ts2) = ts_dict2[uttid]
  192. _align, _align2, _align3 = [], [], []
  193. fts1, fts2 = [], []
  194. _t1, _t2 = [], []
  195. sm = edit_distance.SequenceMatcher(t1.split(','), t2.split(','))
  196. s = sm.get_opcodes()
  197. for j in range(len(s)):
  198. if s[j][0] == "replace" or s[j][0] == "insert":
  199. _align.append(0)
  200. if s[j][0] == "replace" or s[j][0] == "delete":
  201. _align3.append(0)
  202. elif s[j][0] == "equal":
  203. _align.append(1)
  204. _align3.append(1)
  205. else:
  206. continue
  207. # use s to index t2
  208. for a, ts , t in zip(_align, ts2, t2.split(',')):
  209. if a:
  210. fts2.append(ts)
  211. _t2.append(t)
  212. sm2 = edit_distance.SequenceMatcher(t2.split(','), t1.split(','))
  213. s = sm2.get_opcodes()
  214. for j in range(len(s)):
  215. if s[j][0] == "replace" or s[j][0] == "insert":
  216. _align2.append(0)
  217. elif s[j][0] == "equal":
  218. _align2.append(1)
  219. else:
  220. continue
  221. # use s2 tp index t1
  222. for a, ts, t in zip(_align3, ts1, t1.split(',')):
  223. if a:
  224. fts1.append(ts)
  225. _t1.append(t)
  226. if len(fts1) == len(fts2):
  227. shift_time, num_tokens = self._shift(fts1, fts2)
  228. self._accumlated_shift += shift_time
  229. self._accumlated_tokens += num_tokens
  230. if shift_time/num_tokens > self.max_shift:
  231. self.max_shift = shift_time/num_tokens
  232. self.max_shift_uttid = uttid
  233. else:
  234. logging.warning("length mismatch")
  235. return self._accumlated_shift / self._accumlated_tokens
  236. def convert_external_alphas(alphas_file, text_file, output_file):
  237. from funasr.models.predictor.cif import cif_wo_hidden
  238. with open(alphas_file, 'r') as f1, open(text_file, 'r') as f2, open(output_file, 'w') as f3:
  239. for line1, line2 in zip(f1.readlines(), f2.readlines()):
  240. line1 = line1.rstrip()
  241. line2 = line2.rstrip()
  242. assert line1.split()[0] == line2.split()[0]
  243. uttid = line1.split()[0]
  244. alphas = [float(i) for i in line1.split()[1:]]
  245. new_alphas = np.array(remove_chunk_padding(alphas))
  246. new_alphas[-1] += 1e-4
  247. text = line2.split()[1:]
  248. if len(text) + 1 != int(new_alphas.sum()):
  249. # force resize
  250. new_alphas *= (len(text) + 1) / int(new_alphas.sum())
  251. peaks = cif_wo_hidden(torch.Tensor(new_alphas).unsqueeze(0), 1.0-1e-4)
  252. if " " in text:
  253. text = text.split()
  254. else:
  255. text = [i for i in text]
  256. res_str, _ = ts_prediction_lfr6_standard(new_alphas, peaks[0], text,
  257. force_time_shift=-7.0,
  258. sil_in_str=False)
  259. f3.write("{} {}\n".format(uttid, res_str))
  260. def remove_chunk_padding(alphas):
  261. # remove the padding part in alphas if using chunk paraformer for GPU
  262. START_ZERO = 45
  263. MID_ZERO = 75
  264. REAL_FRAMES = 360 # for chunk based encoder 10-120-10 and fsmn padding 5
  265. alphas = alphas[START_ZERO:] # remove the padding at beginning
  266. new_alphas = []
  267. while True:
  268. new_alphas = new_alphas + alphas[:REAL_FRAMES]
  269. alphas = alphas[REAL_FRAMES+MID_ZERO:]
  270. if len(alphas) < REAL_FRAMES: break
  271. return new_alphas
  272. SUPPORTED_MODES = ['cal_aas', 'read_ext_alphas']
  273. def main(args):
  274. if args.mode == 'cal_aas':
  275. asc = AverageShiftCalculator()
  276. asc(args.input, args.input2)
  277. elif args.mode == 'read_ext_alphas':
  278. convert_external_alphas(args.input, args.input2, args.output)
  279. else:
  280. logging.error("Mode {} not in SUPPORTED_MODES: {}.".format(args.mode, SUPPORTED_MODES))
  281. if __name__ == '__main__':
  282. parser = argparse.ArgumentParser(description='timestamp tools')
  283. parser.add_argument('--mode',
  284. default=None,
  285. type=str,
  286. choices=SUPPORTED_MODES,
  287. help='timestamp related toolbox')
  288. parser.add_argument('--input', default=None, type=str, help='input file path')
  289. parser.add_argument('--output', default=None, type=str, help='output file name')
  290. parser.add_argument('--input2', default=None, type=str, help='input2 file path')
  291. parser.add_argument('--kaldi-ts-type',
  292. default='v2',
  293. type=str,
  294. choices=['v0', 'v1', 'v2'],
  295. help='kaldi timestamp to write')
  296. args = parser.parse_args()
  297. main(args)