timestamp_tools.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. res = []
  79. if text_postprocessed is None:
  80. return res
  81. if time_stamp_postprocessed is None:
  82. return res
  83. if len(time_stamp_postprocessed) == 0:
  84. return res
  85. if len(text_postprocessed) == 0:
  86. return res
  87. if punc_id_list is None or len(punc_id_list) == 0:
  88. res.append({
  89. 'text': text_postprocessed.split(),
  90. "start": time_stamp_postprocessed[0][0],
  91. "end": time_stamp_postprocessed[-1][1],
  92. 'text_seg': text_postprocessed.split(),
  93. "ts_list": time_stamp_postprocessed,
  94. })
  95. return res
  96. if len(punc_id_list) != len(time_stamp_postprocessed):
  97. print(" warning length mistach!!!!!!")
  98. sentence_text = ""
  99. sentence_text_seg = ""
  100. ts_list = []
  101. sentence_start = time_stamp_postprocessed[0][0]
  102. sentence_end = time_stamp_postprocessed[0][1]
  103. texts = text_postprocessed.split()
  104. punc_stamp_text_list = list(zip_longest(punc_id_list, time_stamp_postprocessed, texts, fillvalue=None))
  105. for punc_stamp_text in punc_stamp_text_list:
  106. punc_id, time_stamp, text = punc_stamp_text
  107. # sentence_text += text if text is not None else ''
  108. if text is not None:
  109. if 'a' <= text[0] <= 'z' or 'A' <= text[0] <= 'Z':
  110. sentence_text += ' ' + text
  111. elif len(sentence_text) and ('a' <= sentence_text[-1] <= 'z' or 'A' <= sentence_text[-1] <= 'Z'):
  112. sentence_text += ' ' + text
  113. else:
  114. sentence_text += text
  115. sentence_text_seg += text + ' '
  116. ts_list.append(time_stamp)
  117. punc_id = int(punc_id) if punc_id is not None else 1
  118. sentence_end = time_stamp[1] if time_stamp is not None else sentence_end
  119. if punc_id == 2:
  120. sentence_text += ','
  121. res.append({
  122. 'text': sentence_text,
  123. "start": sentence_start,
  124. "end": sentence_end,
  125. "text_seg": sentence_text_seg,
  126. "ts_list": ts_list
  127. })
  128. sentence_text = ''
  129. sentence_text_seg = ''
  130. ts_list = []
  131. sentence_start = sentence_end
  132. elif punc_id == 3:
  133. sentence_text += '.'
  134. res.append({
  135. 'text': sentence_text,
  136. "start": sentence_start,
  137. "end": sentence_end,
  138. "text_seg": sentence_text_seg,
  139. "ts_list": ts_list
  140. })
  141. sentence_text = ''
  142. sentence_text_seg = ''
  143. ts_list = []
  144. sentence_start = sentence_end
  145. elif punc_id == 4:
  146. sentence_text += '?'
  147. res.append({
  148. 'text': sentence_text,
  149. "start": sentence_start,
  150. "end": sentence_end,
  151. "text_seg": sentence_text_seg,
  152. "ts_list": ts_list
  153. })
  154. sentence_text = ''
  155. sentence_text_seg = ''
  156. ts_list = []
  157. sentence_start = sentence_end
  158. return res
  159. class AverageShiftCalculator():
  160. def __init__(self):
  161. logging.warning("Calculating average shift.")
  162. def __call__(self, file1, file2):
  163. uttid_list1, ts_dict1 = self.read_timestamps(file1)
  164. uttid_list2, ts_dict2 = self.read_timestamps(file2)
  165. uttid_intersection = self._intersection(uttid_list1, uttid_list2)
  166. res = self.as_cal(uttid_intersection, ts_dict1, ts_dict2)
  167. logging.warning("Average shift of {} and {}: {}.".format(file1, file2, str(res)[:8]))
  168. logging.warning("Following timestamp pair differs most: {}, detail:{}".format(self.max_shift, self.max_shift_uttid))
  169. def _intersection(self, list1, list2):
  170. set1 = set(list1)
  171. set2 = set(list2)
  172. if set1 == set2:
  173. logging.warning("Uttid same checked.")
  174. return set1
  175. itsc = list(set1 & set2)
  176. logging.warning("Uttid differs: file1 {}, file2 {}, lines same {}.".format(len(list1), len(list2), len(itsc)))
  177. return itsc
  178. def read_timestamps(self, file):
  179. # read timestamps file in standard format
  180. uttid_list = []
  181. ts_dict = {}
  182. with codecs.open(file, 'r') as fin:
  183. for line in fin.readlines():
  184. text = ''
  185. ts_list = []
  186. line = line.rstrip()
  187. uttid = line.split()[0]
  188. uttid_list.append(uttid)
  189. body = " ".join(line.split()[1:])
  190. for pd in body.split(';'):
  191. if not len(pd): continue
  192. # pdb.set_trace()
  193. char, start, end = pd.lstrip(" ").split(' ')
  194. text += char + ','
  195. ts_list.append((float(start), float(end)))
  196. # ts_lists.append(ts_list)
  197. ts_dict[uttid] = (text[:-1], ts_list)
  198. logging.warning("File {} read done.".format(file))
  199. return uttid_list, ts_dict
  200. def _shift(self, filtered_timestamp_list1, filtered_timestamp_list2):
  201. shift_time = 0
  202. for fts1, fts2 in zip(filtered_timestamp_list1, filtered_timestamp_list2):
  203. shift_time += abs(fts1[0] - fts2[0]) + abs(fts1[1] - fts2[1])
  204. num_tokens = len(filtered_timestamp_list1)
  205. return shift_time, num_tokens
  206. def as_cal(self, uttid_list, ts_dict1, ts_dict2):
  207. # calculate average shift between timestamp1 and timestamp2
  208. # when characters differ, use edit distance alignment
  209. # and calculate the error between the same characters
  210. self._accumlated_shift = 0
  211. self._accumlated_tokens = 0
  212. self.max_shift = 0
  213. self.max_shift_uttid = None
  214. for uttid in uttid_list:
  215. (t1, ts1) = ts_dict1[uttid]
  216. (t2, ts2) = ts_dict2[uttid]
  217. _align, _align2, _align3 = [], [], []
  218. fts1, fts2 = [], []
  219. _t1, _t2 = [], []
  220. sm = edit_distance.SequenceMatcher(t1.split(','), t2.split(','))
  221. s = sm.get_opcodes()
  222. for j in range(len(s)):
  223. if s[j][0] == "replace" or s[j][0] == "insert":
  224. _align.append(0)
  225. if s[j][0] == "replace" or s[j][0] == "delete":
  226. _align3.append(0)
  227. elif s[j][0] == "equal":
  228. _align.append(1)
  229. _align3.append(1)
  230. else:
  231. continue
  232. # use s to index t2
  233. for a, ts , t in zip(_align, ts2, t2.split(',')):
  234. if a:
  235. fts2.append(ts)
  236. _t2.append(t)
  237. sm2 = edit_distance.SequenceMatcher(t2.split(','), t1.split(','))
  238. s = sm2.get_opcodes()
  239. for j in range(len(s)):
  240. if s[j][0] == "replace" or s[j][0] == "insert":
  241. _align2.append(0)
  242. elif s[j][0] == "equal":
  243. _align2.append(1)
  244. else:
  245. continue
  246. # use s2 tp index t1
  247. for a, ts, t in zip(_align3, ts1, t1.split(',')):
  248. if a:
  249. fts1.append(ts)
  250. _t1.append(t)
  251. if len(fts1) == len(fts2):
  252. shift_time, num_tokens = self._shift(fts1, fts2)
  253. self._accumlated_shift += shift_time
  254. self._accumlated_tokens += num_tokens
  255. if shift_time/num_tokens > self.max_shift:
  256. self.max_shift = shift_time/num_tokens
  257. self.max_shift_uttid = uttid
  258. else:
  259. logging.warning("length mismatch")
  260. return self._accumlated_shift / self._accumlated_tokens
  261. def convert_external_alphas(alphas_file, text_file, output_file):
  262. from funasr.models.predictor.cif import cif_wo_hidden
  263. with open(alphas_file, 'r') as f1, open(text_file, 'r') as f2, open(output_file, 'w') as f3:
  264. for line1, line2 in zip(f1.readlines(), f2.readlines()):
  265. line1 = line1.rstrip()
  266. line2 = line2.rstrip()
  267. assert line1.split()[0] == line2.split()[0]
  268. uttid = line1.split()[0]
  269. alphas = [float(i) for i in line1.split()[1:]]
  270. new_alphas = np.array(remove_chunk_padding(alphas))
  271. new_alphas[-1] += 1e-4
  272. text = line2.split()[1:]
  273. if len(text) + 1 != int(new_alphas.sum()):
  274. # force resize
  275. new_alphas *= (len(text) + 1) / int(new_alphas.sum())
  276. peaks = cif_wo_hidden(torch.Tensor(new_alphas).unsqueeze(0), 1.0-1e-4)
  277. if " " in text:
  278. text = text.split()
  279. else:
  280. text = [i for i in text]
  281. res_str, _ = ts_prediction_lfr6_standard(new_alphas, peaks[0], text,
  282. force_time_shift=-7.0,
  283. sil_in_str=False)
  284. f3.write("{} {}\n".format(uttid, res_str))
  285. def remove_chunk_padding(alphas):
  286. # remove the padding part in alphas if using chunk paraformer for GPU
  287. START_ZERO = 45
  288. MID_ZERO = 75
  289. REAL_FRAMES = 360 # for chunk based encoder 10-120-10 and fsmn padding 5
  290. alphas = alphas[START_ZERO:] # remove the padding at beginning
  291. new_alphas = []
  292. while True:
  293. new_alphas = new_alphas + alphas[:REAL_FRAMES]
  294. alphas = alphas[REAL_FRAMES+MID_ZERO:]
  295. if len(alphas) < REAL_FRAMES: break
  296. return new_alphas
  297. SUPPORTED_MODES = ['cal_aas', 'read_ext_alphas']
  298. def main(args):
  299. if args.mode == 'cal_aas':
  300. asc = AverageShiftCalculator()
  301. asc(args.input, args.input2)
  302. elif args.mode == 'read_ext_alphas':
  303. convert_external_alphas(args.input, args.input2, args.output)
  304. else:
  305. logging.error("Mode {} not in SUPPORTED_MODES: {}.".format(args.mode, SUPPORTED_MODES))
  306. if __name__ == '__main__':
  307. parser = argparse.ArgumentParser(description='timestamp tools')
  308. parser.add_argument('--mode',
  309. default=None,
  310. type=str,
  311. choices=SUPPORTED_MODES,
  312. help='timestamp related toolbox')
  313. parser.add_argument('--input', default=None, type=str, help='input file path')
  314. parser.add_argument('--output', default=None, type=str, help='output file name')
  315. parser.add_argument('--input2', default=None, type=str, help='input2 file path')
  316. parser.add_argument('--kaldi-ts-type',
  317. default='v2',
  318. type=str,
  319. choices=['v0', 'v1', 'v2'],
  320. help='kaldi timestamp to write')
  321. args = parser.parse_args()
  322. main(args)