dlxj commited on
Commit
09d2296
·
1 Parent(s): 52f4978

给 CTC 强行加上时间输出

Browse files
examples/asr/asr_cache_aware_streaming/speech_to_text_cache_aware_streaming_infer.py CHANGED
@@ -115,7 +115,7 @@ from nemo.collections.asr.parts.submodules.rnnt_decoding import RNNTDecodingConf
115
  from nemo.collections.asr.parts.utils.manifest_utils import read_manifest
116
  from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis
117
  from nemo.collections.asr.parts.utils.streaming_utils import CacheAwareStreamingAudioBuffer
118
- from nemo.collections.asr.parts.utils.transcribe_utils import setup_model
119
  from nemo.core.config import hydra_runner
120
  from nemo.utils import logging
121
 
@@ -173,9 +173,9 @@ class TranscriptionConfig:
173
  matmul_precision: str = "high" # Literal["highest", "high", "medium"]
174
 
175
  # Decoding strategy for CTC models
176
- ctc_decoding: CTCDecodingConfig = field(default_factory=CTCDecodingConfig)
177
  # Decoding strategy for RNNT models
178
- rnnt_decoding: RNNTDecodingConfig = field(default_factory=lambda: RNNTDecodingConfig(fused_batch_size=-1))
179
  # Selects the decoder for Hybrid ASR models which has both the CTC and RNNT decoder.
180
  decoder_type: Optional[str] = None # Literal["ctc", "rnnt"]
181
 
@@ -187,17 +187,26 @@ class TranscriptionConfig:
187
  debug_mode: bool = False # Whether to print more detail in the output.
188
 
189
 
190
- def extract_transcriptions(hyps):
191
  """
192
  The transcribed_texts returned by CTC and RNNT models are different.
193
  This method would extract and return the text section of the hypothesis.
194
  """
195
  if isinstance(hyps[0], Hypothesis):
196
  transcriptions = []
 
197
  for hyp in hyps:
198
  transcriptions.append(hyp.text)
 
 
 
 
 
 
199
  else:
200
  transcriptions = hyps
 
 
201
  return transcriptions
202
 
203
 
@@ -272,13 +281,53 @@ def perform_streaming(
272
  previous_hypotheses=previous_hypotheses,
273
  previous_pred_out=pred_out_stream,
274
  drop_extra_pre_encoded=calc_drop_extra_pre_encoded(asr_model, step_num, pad_and_drop_preencoded),
275
- return_transcription=True,
276
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
 
278
  if debug_mode:
279
- logging.info(f"Streaming transcriptions: {extract_transcriptions(transcribed_texts)}")
280
-
281
- final_streaming_tran = extract_transcriptions(transcribed_texts)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  logging.info(f"Final streaming transcriptions: {final_streaming_tran}")
283
 
284
  if compare_vs_offline:
@@ -296,7 +345,7 @@ def perform_streaming(
296
  f"The shape of the outputs of the model in streaming mode ({pred_out_stream_cat.size()}) is different from offline mode ({pred_out_offline_cat.size()})."
297
  )
298
 
299
- return final_streaming_tran, final_offline_tran
300
 
301
 
302
  @hydra_runner(config_name="TranscriptionConfig", schema=TranscriptionConfig)
@@ -373,6 +422,13 @@ def main(cfg: TranscriptionConfig):
373
  asr_model.change_decoding_strategy(cfg.rnnt_decoding)
374
  else:
375
  asr_model.change_decoding_strategy(cfg.ctc_decoding)
 
 
 
 
 
 
 
376
 
377
  asr_model = asr_model.to(device=device, dtype=compute_dtype)
378
  asr_model.eval()
@@ -411,7 +467,7 @@ def main(cfg: TranscriptionConfig):
411
  if cfg.audio_file is not None:
412
  # stream a single audio file
413
  _ = streaming_buffer.append_audio_file(cfg.audio_file, stream_id=-1)
414
- perform_streaming(
415
  asr_model=asr_model,
416
  streaming_buffer=streaming_buffer,
417
  compute_dtype=compute_dtype,
@@ -419,12 +475,20 @@ def main(cfg: TranscriptionConfig):
419
  debug_mode=cfg.debug_mode,
420
  pad_and_drop_preencoded=cfg.pad_and_drop_preencoded,
421
  )
 
 
 
 
 
 
 
422
  # return early for single file mode
423
  return
424
  else:
425
  # stream audio files in a manifest file in batched mode
426
  all_streaming_tran = []
427
  all_offline_tran = []
 
428
  all_refs_text = []
429
  batch_size = cfg.batch_size
430
 
@@ -460,7 +524,7 @@ def main(cfg: TranscriptionConfig):
460
  logging.info(
461
  f"Starting to stream samples {sample_idx - len(streaming_buffer) + 1} to {sample_idx}..."
462
  )
463
- streaming_tran, offline_tran = perform_streaming(
464
  asr_model=asr_model,
465
  streaming_buffer=streaming_buffer,
466
  compute_dtype=compute_dtype,
@@ -469,6 +533,7 @@ def main(cfg: TranscriptionConfig):
469
  pad_and_drop_preencoded=cfg.pad_and_drop_preencoded,
470
  )
471
  all_streaming_tran.extend(streaming_tran)
 
472
  if cfg.compare_vs_offline:
473
  all_offline_tran.extend(offline_tran)
474
  streaming_buffer.reset_buffer()
@@ -489,14 +554,19 @@ def main(cfg: TranscriptionConfig):
489
 
490
  hyp_json = os.path.join(cfg.output_path, fname)
491
  os.makedirs(cfg.output_path, exist_ok=True)
492
- with open(hyp_json, "w") as out_f:
493
  for i, hyp in enumerate(all_streaming_tran):
494
  record = {
495
  "pred_text": hyp,
496
  "text": all_refs_text[i],
497
  "wer": round(word_error_rate(hypotheses=[hyp], references=[all_refs_text[i]]) * 100, 2),
498
  }
499
- out_f.write(json.dumps(record) + '\n')
 
 
 
 
 
500
 
501
 
502
  if __name__ == '__main__':
 
115
  from nemo.collections.asr.parts.utils.manifest_utils import read_manifest
116
  from nemo.collections.asr.parts.utils.rnnt_utils import Hypothesis
117
  from nemo.collections.asr.parts.utils.streaming_utils import CacheAwareStreamingAudioBuffer
118
+ from nemo.collections.asr.parts.utils.transcribe_utils import setup_model, normalize_timestamp_output, process_timestamp_outputs
119
  from nemo.core.config import hydra_runner
120
  from nemo.utils import logging
121
 
 
173
  matmul_precision: str = "high" # Literal["highest", "high", "medium"]
174
 
175
  # Decoding strategy for CTC models
176
+ ctc_decoding: CTCDecodingConfig = field(default_factory=lambda: CTCDecodingConfig(compute_timestamps=True))
177
  # Decoding strategy for RNNT models
178
+ rnnt_decoding: RNNTDecodingConfig = field(default_factory=lambda: RNNTDecodingConfig(fused_batch_size=-1, compute_timestamps=True))
179
  # Selects the decoder for Hybrid ASR models which has both the CTC and RNNT decoder.
180
  decoder_type: Optional[str] = None # Literal["ctc", "rnnt"]
181
 
 
187
  debug_mode: bool = False # Whether to print more detail in the output.
188
 
189
 
190
+ def extract_transcriptions(hyps, return_timestamps=False):
191
  """
192
  The transcribed_texts returned by CTC and RNNT models are different.
193
  This method would extract and return the text section of the hypothesis.
194
  """
195
  if isinstance(hyps[0], Hypothesis):
196
  transcriptions = []
197
+ timestamps = []
198
  for hyp in hyps:
199
  transcriptions.append(hyp.text)
200
+ if hasattr(hyp, 'timestamp') and hyp.timestamp:
201
+ timestamps.append(hyp.timestamp)
202
+ else:
203
+ timestamps.append(None)
204
+ if return_timestamps:
205
+ return transcriptions, timestamps
206
  else:
207
  transcriptions = hyps
208
+ if return_timestamps:
209
+ return transcriptions, [None] * len(transcriptions)
210
  return transcriptions
211
 
212
 
 
281
  previous_hypotheses=previous_hypotheses,
282
  previous_pred_out=pred_out_stream,
283
  drop_extra_pre_encoded=calc_drop_extra_pre_encoded(asr_model, step_num, pad_and_drop_preencoded),
284
+ return_transcription=False, # 关闭默认的简单文本解码
285
  )
286
+
287
+ # 显式使用带有 return_hypotheses=True 的完整解码
288
+ if hasattr(asr_model, 'ctc_decoder'):
289
+ decoding = asr_model.ctc_decoding
290
+ else:
291
+ decoding = asr_model.decoding
292
+
293
+ transcribed_texts = []
294
+ for preds_idx, preds_concat in enumerate(pred_out_stream):
295
+ encoded_len = torch.tensor([len(preds_concat)], device=preds_concat.device)
296
+ decoded_out = decoding.ctc_decoder_predictions_tensor(
297
+ decoder_outputs=preds_concat.unsqueeze(0),
298
+ decoder_lengths=encoded_len,
299
+ return_hypotheses=True,
300
+ )
301
+ # decoded_out is a list of list of Hypotheses or a list of Hypotheses depending on batch
302
+ if isinstance(decoded_out[0], list):
303
+ transcribed_texts.append(decoded_out[0][0])
304
+ else:
305
+ transcribed_texts.append(decoded_out[0])
306
 
307
  if debug_mode:
308
+ current_texts = extract_transcriptions(transcribed_texts)
309
+ # 实时打印每个 chunk 的结果
310
+ print(f"\r[Streaming Step {step_num}] {current_texts[0]}", end='', flush=True)
311
+ # logging.info(f"Streaming transcriptions: {extract_transcriptions(transcribed_texts)}")
312
+
313
+ print() # 换行
314
+ final_streaming_tran, final_streaming_timestamps = extract_transcriptions(transcribed_texts, return_timestamps=True)
315
+
316
+ # 获取模型的降采样率和帧移
317
+ if hasattr(asr_model.cfg, 'preprocessor'):
318
+ window_stride = asr_model.cfg.preprocessor.get('window_stride', 0.01)
319
+ else:
320
+ window_stride = 0.01
321
+
322
+ subsampling_factor = 1
323
+ if hasattr(asr_model, 'encoder') and hasattr(asr_model.encoder, 'subsampling_factor'):
324
+ subsampling_factor = asr_model.encoder.subsampling_factor
325
+ elif hasattr(asr_model, 'encoder') and hasattr(asr_model.encoder, 'conv_subsampling_factor'):
326
+ subsampling_factor = asr_model.encoder.conv_subsampling_factor
327
+
328
+ # 对结果进行时间戳转换
329
+ process_timestamp_outputs(transcribed_texts, subsampling_factor=subsampling_factor, window_stride=window_stride)
330
+
331
  logging.info(f"Final streaming transcriptions: {final_streaming_tran}")
332
 
333
  if compare_vs_offline:
 
345
  f"The shape of the outputs of the model in streaming mode ({pred_out_stream_cat.size()}) is different from offline mode ({pred_out_offline_cat.size()})."
346
  )
347
 
348
+ return final_streaming_tran, final_offline_tran, final_streaming_timestamps
349
 
350
 
351
  @hydra_runner(config_name="TranscriptionConfig", schema=TranscriptionConfig)
 
422
  asr_model.change_decoding_strategy(cfg.rnnt_decoding)
423
  else:
424
  asr_model.change_decoding_strategy(cfg.ctc_decoding)
425
+
426
+ # 强制开启时间戳计算(针对某些模型可能未正确应用配置的情况)
427
+ if hasattr(asr_model.decoding, 'compute_timestamps'):
428
+ asr_model.decoding.compute_timestamps = True
429
+ if hasattr(asr_model.decoding, 'ctc_decoder') and hasattr(asr_model.decoding.ctc_decoder, 'compute_timestamps'):
430
+ asr_model.decoding.ctc_decoder.compute_timestamps = True
431
+ asr_model.decoding.ctc_decoder.return_hypotheses = True
432
 
433
  asr_model = asr_model.to(device=device, dtype=compute_dtype)
434
  asr_model.eval()
 
467
  if cfg.audio_file is not None:
468
  # stream a single audio file
469
  _ = streaming_buffer.append_audio_file(cfg.audio_file, stream_id=-1)
470
+ streaming_tran, offline_tran, streaming_timestamps = perform_streaming(
471
  asr_model=asr_model,
472
  streaming_buffer=streaming_buffer,
473
  compute_dtype=compute_dtype,
 
475
  debug_mode=cfg.debug_mode,
476
  pad_and_drop_preencoded=cfg.pad_and_drop_preencoded,
477
  )
478
+
479
+ # 打印单个文件的时间戳
480
+ if streaming_timestamps and streaming_timestamps[0]:
481
+ for key, val in streaming_timestamps[0].items():
482
+ if key != 'timestep':
483
+ logging.info(f"Timestamps {key}: {normalize_timestamp_output(val)}")
484
+
485
  # return early for single file mode
486
  return
487
  else:
488
  # stream audio files in a manifest file in batched mode
489
  all_streaming_tran = []
490
  all_offline_tran = []
491
+ all_streaming_timestamps = []
492
  all_refs_text = []
493
  batch_size = cfg.batch_size
494
 
 
524
  logging.info(
525
  f"Starting to stream samples {sample_idx - len(streaming_buffer) + 1} to {sample_idx}..."
526
  )
527
+ streaming_tran, offline_tran, streaming_timestamps = perform_streaming(
528
  asr_model=asr_model,
529
  streaming_buffer=streaming_buffer,
530
  compute_dtype=compute_dtype,
 
533
  pad_and_drop_preencoded=cfg.pad_and_drop_preencoded,
534
  )
535
  all_streaming_tran.extend(streaming_tran)
536
+ all_streaming_timestamps.extend(streaming_timestamps)
537
  if cfg.compare_vs_offline:
538
  all_offline_tran.extend(offline_tran)
539
  streaming_buffer.reset_buffer()
 
554
 
555
  hyp_json = os.path.join(cfg.output_path, fname)
556
  os.makedirs(cfg.output_path, exist_ok=True)
557
+ with open(hyp_json, "w", encoding='utf-8') as out_f:
558
  for i, hyp in enumerate(all_streaming_tran):
559
  record = {
560
  "pred_text": hyp,
561
  "text": all_refs_text[i],
562
  "wer": round(word_error_rate(hypotheses=[hyp], references=[all_refs_text[i]]) * 100, 2),
563
  }
564
+ if all_streaming_timestamps[i]:
565
+ for key, val in all_streaming_timestamps[i].items():
566
+ if key != 'timestep':
567
+ record[f'{key}'] = normalize_timestamp_output(val)
568
+
569
+ out_f.write(json.dumps(record, ensure_ascii=False) + '\n')
570
 
571
 
572
  if __name__ == '__main__':
readme.txt CHANGED
@@ -242,6 +242,60 @@ python examples/asr/asr_cache_aware_streaming/speech_to_text_cache_aware_streami
242
 
243
 
244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  如果要训练一个 ASR 语音识别大模型,只用一条数据,它既是训练集,又是验证集,又是测试集。这样它正确率能正 100% 吗
246
 
247
 
 
242
 
243
 
244
 
245
+
246
+ 它是不是真的流式输入,流式输出,为什么它是一下子打印全部结果,而不是边推理边输出部分结果 `examples\asr\asr_cache_aware_streaming\speech_to_text_cache_aware_streaming_infer.py`
247
+
248
+ 它**确实是真流式**的(前提是你用了支持 Cache-aware 的模型并搭配这个脚本)。
249
+
250
+ 它的运行机制是:
251
+ 1. `CacheAwareStreamingAudioBuffer` 将输入的音频切割成一个个非常小的片段(Chunk,例如每次 0.08 秒 或 0.16 秒)。
252
+ 2. 在 `perform_streaming` 函数中,有一个 `for step_num, (chunk_audio, chunk_lengths) in enumerate(streaming_buffer_iter):` 的循环。
253
+ 3. 它在每一次循环中,只把当前这个小 chunk 喂给模型 (`asr_model.conformer_stream_step`),模型结合上一次循环保存的历史状态(Cache)吐出当前的识别结果。
254
+
255
+ **那为什么它是一下子打印全部结果?**
256
+ 这是因为在原版脚本中,如果你不开启 `debug_mode=true`,它就不会在内部循环打印;即便是开启了 `debug_mode=true`,原版代码使用的 `logging.info()` 也是每一行单独打印,或者因为音频太短执行太快,让你产生了一次性输出的错觉。它主要被设计用来“批量验证流式模型的最终识别准确率”,所以更侧重于输出最终结果(`Final streaming transcriptions`)。
257
+
258
+ ### 我已经帮你修改了脚本
259
+ 为了让你有更直观的“边说边出字”的实时流式体验,我修改了 [speech_to_text_cache_aware_streaming_infer.py](file:///e:/huggingface_echodict/NeMo/examples/asr/asr_cache_aware_streaming/speech_to_text_cache_aware_streaming_infer.py) 中的打印逻辑。
260
+
261
+ 现在,只要你**确保参数中带有 `debug_mode=true`**,它就会在终端的同一行动态刷新当前已识别的文本(就像你在看语音输入法打字那样):
262
+
263
+ ```python
264
+ [Streaming Step 0]
265
+ [Streaming Step 1] 私
266
+ [Streaming Step 2] 私はな
267
+ ...
268
+ [Streaming Step 45] 私はなぜか答えられなかった。
269
+ ```
270
+ 你可以再次运行试试看这个“打字机”效果!
271
+
272
+
273
+
274
+ 这里的 timestep 是这样的,为什么不是时间 'timestep' =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] `examples\asr\asr_cache_aware_streaming\speech_to_text_cache_aware_streaming_infer.py#L201-201`
275
+
276
+ 你看到的那一串数字并不是时间,而是**模型预测结果在特征序列上的索引(Frames / Timesteps)**。
277
+
278
+ 在 CTC 或者 RNNT 模型中:
279
+ - 语音信号首先被切成一帧一帧的特征(比如每 10ms 一帧)。
280
+ - 然后经过前端卷积网络进行降采样(比如 4倍 下采样),意味着进入模型的特征序列缩短为每 40ms 一个 timestep。
281
+ - `timestep` 里记录的 `[0, 1, 2, ...]` 就是指网络在第 0 帧、第 1 帧、第 2 帧输出了对应的文字(token)。
282
+
283
+ **要将它们转换为实际时间(秒),需要进行换算:**
284
+ `时间 (秒) = timestep * window_stride (特征帧移,通常是 0.01秒) * subsampling_factor (模型降采样倍数,通常是 4)`
285
+
286
+ ### 我已经帮你加了换算代码
287
+ 我已经修改了 [speech_to_text_cache_aware_streaming_infer.py](file:///e:/huggingface_echodict/NeMo/examples/asr/asr_cache_aware_streaming/speech_to_text_cache_aware_streaming_infer.py) 脚本。
288
+
289
+ 我引入了 NeMo 内置的 `process_timestamp_outputs` 函数,并在推理结束后:
290
+ 1. 自动读取你模型的 `window_stride` 和 `subsampling_factor`。
291
+ 2. 调用函数将原本的 `start_offset` 和 `end_offset`(帧索引)换算为了具体的 `start` 和 `end` (实际物理时间,单位为秒)。
292
+
293
+ 你现在重新运行一下脚本,输出里的时间戳应该就会多出 `start` 和 `end` 字段,它们就是你想要的实际时间了!
294
+
295
+
296
+
297
+
298
+
299
  如果要训练一个 ASR 语音识别大模型,只用一条数据,它既是训练集,又是验证集,又是测试集。这样它正确率能正 100% 吗
300
 
301