dlxj commited on
Commit
7a12a78
·
1 Parent(s): 66ba09a

add server_aware_streaming.py 成功推理 RNNT 的 nemotron-speech-streaming-en-0.6b ,理论上同时兼容 CTC

Browse files
Files changed (2) hide show
  1. server_aware_streaming.py +815 -0
  2. test_websocket_client.py +182 -0
server_aware_streaming.py ADDED
@@ -0,0 +1,815 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WebSocket ASR server for Nemotron-Speech with true incremental streaming and timestamps."""
2
+
3
+ import asyncio
4
+ import argparse
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from dataclasses import dataclass, field
9
+ from typing import Any, Optional, Tuple
10
+
11
+ import numpy as np
12
+ import torch
13
+ from aiohttp import web, WSMsgType
14
+ from loguru import logger
15
+
16
+ from nemo.collections.asr.parts.utils.transcribe_utils import normalize_timestamp_output, process_timestamp_outputs
17
+
18
+ # Enable debug logging with DEBUG_ASR=1
19
+ DEBUG_ASR = os.environ.get("DEBUG_ASR", "0") == "1"
20
+
21
+
22
+ def _hash_audio(audio: np.ndarray) -> str:
23
+ """Get short hash of audio array for debugging."""
24
+ if audio is None or len(audio) == 0:
25
+ return "empty"
26
+ return hashlib.md5(audio.tobytes()).hexdigest()[:8]
27
+
28
+
29
+ DEFAULT_MODEL = "./nemotron-speech-streaming-en-0.6b/nemotron-speech-streaming-en-0.6b.nemo"
30
+ # DEFAULT_MODEL = "results/NeMo_Ja_FastConformer_Streaming/checkpoints/NeMo_Ja_FastConformer_Streaming.nemo"
31
+
32
+
33
+ # Right context options for att_context_size=[70, X]
34
+ RIGHT_CONTEXT_OPTIONS = {
35
+ 0: "~80ms ultra-low latency",
36
+ 1: "~160ms low latency (recommended)",
37
+ 6: "~560ms balanced",
38
+ 13: "~1.12s highest accuracy",
39
+ }
40
+
41
+
42
+ @dataclass
43
+ class ASRSession:
44
+ """Per-connection session state with caches for true incremental streaming."""
45
+
46
+ id: str
47
+ websocket: Any
48
+
49
+ # Accumulated audio buffer (all audio received so far)
50
+ accumulated_audio: Optional[np.ndarray] = None
51
+
52
+ # Number of mel frames already emitted to encoder
53
+ emitted_frames: int = 0
54
+
55
+ # Encoder cache state
56
+ cache_last_channel: Optional[torch.Tensor] = None
57
+ cache_last_time: Optional[torch.Tensor] = None
58
+ cache_last_channel_len: Optional[torch.Tensor] = None
59
+
60
+ # Decoder state
61
+ previous_hypotheses: Any = None
62
+ pred_out_stream: Any = None
63
+
64
+ # Current transcription (model's cumulative output)
65
+ current_text: str = ""
66
+
67
+ # Current timestamps
68
+ current_timestamps: Optional[dict] = None
69
+
70
+ # Last text emitted to client on hard reset (for server-side deduplication)
71
+ # We only send the delta (new portion) to avoid downstream duplication
72
+ last_emitted_text: str = ""
73
+
74
+ # Audio overlap buffer for mid-utterance reset continuity
75
+ # This preserves the last N ms of audio to provide encoder left-context
76
+ # when a new segment starts after a reset
77
+ overlap_buffer: Optional[np.ndarray] = None
78
+
79
+
80
+ class ASRServer:
81
+ """WebSocket server for streaming ASR with true incremental processing."""
82
+
83
+ def __init__(
84
+ self,
85
+ model: str,
86
+ host: str = "0.0.0.0",
87
+ port: int = 8080,
88
+ right_context: int = 1,
89
+ ):
90
+ self.model_name_or_path = model
91
+ self.host = host
92
+ self.port = port
93
+ self.right_context = right_context
94
+ self.model = None
95
+ self.sample_rate = 16000
96
+
97
+ # Inference lock
98
+ self.inference_lock = asyncio.Lock()
99
+
100
+ # Active sessions
101
+ self.sessions: dict[str, ASRSession] = {}
102
+
103
+ # Model loaded flag for health check
104
+ self.model_loaded = False
105
+
106
+ # Streaming parameters (calculated from model config)
107
+ self.shift_frames = None
108
+ self.pre_encode_cache_size = None
109
+ self.hop_samples = None
110
+
111
+ # Audio overlap for mid-utterance reset continuity (calculated in load_model)
112
+ self.overlap_samples = None
113
+
114
+ def load_model(self):
115
+ """Load the NeMo ASR model with streaming configuration."""
116
+ import nemo.collections.asr as nemo_asr
117
+ from omegaconf import OmegaConf
118
+
119
+ # Detect if model is a local .nemo file or HuggingFace model name
120
+ is_local_file = (
121
+ self.model_name_or_path.endswith('.nemo') or
122
+ os.path.exists(self.model_name_or_path)
123
+ )
124
+
125
+ if is_local_file:
126
+ logger.info(f"Loading model from local file: {self.model_name_or_path}")
127
+ self.model = nemo_asr.models.ASRModel.restore_from(
128
+ self.model_name_or_path, map_location='cpu'
129
+ )
130
+ else:
131
+ logger.info(f"Loading model from HuggingFace: {self.model_name_or_path}")
132
+ self.model = nemo_asr.models.ASRModel.from_pretrained(
133
+ self.model_name_or_path, map_location='cpu'
134
+ )
135
+ self.model = self.model.cuda()
136
+
137
+ # Configure attention context for streaming
138
+ logger.info(f"Setting att_context_size=[70, {self.right_context}] ({RIGHT_CONTEXT_OPTIONS.get(self.right_context, 'custom')})")
139
+ if hasattr(self.model.encoder, "set_default_att_context_size"):
140
+ self.model.encoder.set_default_att_context_size([70, self.right_context])
141
+
142
+ # Configure greedy decoding (required for Blackwell GPU)
143
+ logger.info("Configuring greedy decoding for Blackwell compatibility and enabling timestamps...")
144
+
145
+ # Check model type to set preserve_alignments
146
+ preserve_alignments = False
147
+ if hasattr(self.model, 'joint'): # RNNT model
148
+ preserve_alignments = True
149
+
150
+ decoding_cfg_dict = {
151
+ 'strategy': 'greedy',
152
+ 'greedy': {
153
+ 'max_symbols': 10,
154
+ 'loop_labels': False,
155
+ 'use_cuda_graph_decoder': False,
156
+ },
157
+ 'compute_timestamps': True
158
+ }
159
+
160
+ if preserve_alignments:
161
+ decoding_cfg_dict['preserve_alignments'] = True
162
+
163
+ self.model.change_decoding_strategy(
164
+ decoding_cfg=OmegaConf.create(decoding_cfg_dict)
165
+ )
166
+
167
+ # Force enable timestamps
168
+ if hasattr(self.model, 'decoding'):
169
+ if hasattr(self.model.decoding, 'compute_timestamps'):
170
+ self.model.decoding.compute_timestamps = True
171
+ if hasattr(self.model.decoding, 'preserve_alignments'):
172
+ self.model.decoding.preserve_alignments = preserve_alignments
173
+ if hasattr(self.model.decoding, 'ctc_decoder') and hasattr(self.model.decoding.ctc_decoder, 'compute_timestamps'):
174
+ self.model.decoding.ctc_decoder.compute_timestamps = True
175
+ self.model.decoding.ctc_decoder.return_hypotheses = True
176
+
177
+ # Force RNNT decoder settings if present
178
+ if hasattr(self.model, 'joint'):
179
+ if hasattr(self.model.decoding, 'rnnt_decoder_predictions_tensor'):
180
+ if hasattr(self.model.decoding, 'compute_timestamps'):
181
+ # We MUST set this to False during the stream step,
182
+ # otherwise the internal `rnnt_decoder_predictions_tensor` will try to compute
183
+ # timestamps on partial chunks and fail with length mismatch ValueError.
184
+ # We will manually compute the timestamps later in `_process_chunk` / `_process_final_chunk`
185
+ self.model.decoding.compute_timestamps = False
186
+ if hasattr(self.model.decoding, 'preserve_alignments'):
187
+ self.model.decoding.preserve_alignments = True
188
+ if hasattr(self.model.decoding, 'return_hypotheses'):
189
+ self.model.decoding.return_hypotheses = True
190
+
191
+ self.model.eval()
192
+
193
+ # Disable dither for deterministic preprocessing
194
+ self.model.preprocessor.featurizer.dither = 0.0
195
+
196
+ # Get streaming config
197
+ scfg = self.model.encoder.streaming_cfg
198
+ logger.info(f"Streaming config: chunk_size={scfg.chunk_size}, shift_size={scfg.shift_size}")
199
+
200
+ # Calculate parameters
201
+ preprocessor_cfg = self.model.cfg.preprocessor
202
+ hop_length_sec = preprocessor_cfg.get('window_stride', 0.01)
203
+ self.hop_samples = int(hop_length_sec * self.sample_rate)
204
+
205
+ # shift_size[1] = 16 frames for 160ms chunks
206
+ self.shift_frames = scfg.shift_size[1] if isinstance(scfg.shift_size, list) else scfg.shift_size
207
+
208
+ # pre_encode_cache_size[1] = 9 frames
209
+ pre_cache = scfg.pre_encode_cache_size
210
+ self.pre_encode_cache_size = pre_cache[1] if isinstance(pre_cache, list) else pre_cache
211
+
212
+ # drop_extra_pre_encoded for non-first chunks
213
+ self.drop_extra = scfg.drop_extra_pre_encoded
214
+
215
+ # Calculate silence padding for final chunk:
216
+ # - right_context chunks for encoder lookahead
217
+ # - 1 additional chunk for decoder finalization
218
+ # With right_context=1, this is (1+1)*160ms = 320ms
219
+ self.final_padding_frames = (self.right_context + 1) * self.shift_frames
220
+ padding_ms = self.final_padding_frames * hop_length_sec * 1000
221
+
222
+ # Calculate audio overlap for mid-utterance reset continuity
223
+ # Use pre_encode_cache_size frames = 90ms of left-context
224
+ # This allows the encoder to have proper context when starting a new segment
225
+ self.overlap_samples = self.pre_encode_cache_size * self.hop_samples
226
+ overlap_ms = self.overlap_samples * 1000 / self.sample_rate
227
+
228
+ shift_ms = self.shift_frames * hop_length_sec * 1000
229
+ logger.info(f"Model loaded: {type(self.model).__name__}")
230
+ logger.info(f"Shift size: {shift_ms:.0f}ms ({self.shift_frames} frames)")
231
+ logger.info(f"Pre-encode cache: {self.pre_encode_cache_size} frames")
232
+ logger.info(f"Final chunk padding: {padding_ms:.0f}ms ({self.final_padding_frames} frames)")
233
+ logger.info(f"Audio overlap for resets: {overlap_ms:.0f}ms ({self.overlap_samples} samples)")
234
+
235
+ # Warmup inference to ensure model is fully loaded on GPU
236
+ # This prevents GPU memory issues when LLM starts later
237
+ self._warmup()
238
+
239
+ def _warmup(self):
240
+ """Run warmup inference using streaming API to claim GPU memory."""
241
+ import time
242
+
243
+ logger.info("Running warmup inference (streaming API) to claim GPU memory...")
244
+ start = time.perf_counter()
245
+
246
+ # Generate 1 second of silence plus padding for warmup
247
+ warmup_samples = self.sample_rate + (self.final_padding_frames * self.hop_samples)
248
+ warmup_audio = np.zeros(warmup_samples, dtype=np.float32)
249
+
250
+ # Run streaming inference to force all CUDA kernels to compile
251
+ with torch.inference_mode():
252
+ audio_tensor = torch.from_numpy(warmup_audio).unsqueeze(0).cuda()
253
+ audio_len = torch.tensor([len(warmup_audio)], device='cuda')
254
+
255
+ # Preprocess
256
+ mel, mel_len = self.model.preprocessor(input_signal=audio_tensor, length=audio_len)
257
+
258
+ # Get initial cache
259
+ cache = self.model.encoder.get_initial_cache_state(batch_size=1)
260
+
261
+ # Run streaming step (processes entire mel as one chunk)
262
+ _ = self.model.conformer_stream_step(
263
+ processed_signal=mel,
264
+ processed_signal_length=mel_len,
265
+ cache_last_channel=cache[0],
266
+ cache_last_time=cache[1],
267
+ cache_last_channel_len=cache[2],
268
+ keep_all_outputs=True,
269
+ previous_hypotheses=None,
270
+ previous_pred_out=None,
271
+ drop_extra_pre_encoded=0,
272
+ return_transcription=True,
273
+ )
274
+
275
+ elapsed = (time.perf_counter() - start) * 1000
276
+ logger.info(f"Warmup complete in {elapsed:.0f}ms - GPU memory claimed")
277
+
278
+ def _init_session(self, session: ASRSession):
279
+ """Initialize a fresh session."""
280
+ # Initialize encoder cache
281
+ cache = self.model.encoder.get_initial_cache_state(batch_size=1)
282
+ session.cache_last_channel = cache[0]
283
+ session.cache_last_time = cache[1]
284
+ session.cache_last_channel_len = cache[2]
285
+
286
+ # Reset audio buffer and frame counter
287
+ if session.overlap_buffer is not None and len(session.overlap_buffer) > 0:
288
+ session.accumulated_audio = session.overlap_buffer.copy()
289
+ overlap_ms = len(session.overlap_buffer) * 1000 / self.sample_rate
290
+ logger.debug(
291
+ f"Session {session.id}: prepending {len(session.overlap_buffer)} samples "
292
+ f"({overlap_ms:.0f}ms) of overlap audio"
293
+ )
294
+ session.overlap_buffer = None # Clear after use
295
+ else:
296
+ session.accumulated_audio = np.array([], dtype=np.float32)
297
+
298
+ session.emitted_frames = 0
299
+
300
+ # Reset decoder state
301
+ session.previous_hypotheses = None
302
+ session.pred_out_stream = None
303
+ session.current_text = ""
304
+ session.current_timestamps = None
305
+
306
+ async def websocket_handler(self, request: web.Request) -> web.WebSocketResponse:
307
+ """Handle a WebSocket client connection."""
308
+ import uuid
309
+
310
+ ws = web.WebSocketResponse(max_msg_size=10 * 1024 * 1024)
311
+ await ws.prepare(request)
312
+
313
+ session_id = str(uuid.uuid4())[:8]
314
+ session = ASRSession(id=session_id, websocket=ws)
315
+ self.sessions[session_id] = session
316
+
317
+ logger.info(f"Client {session_id} connected")
318
+
319
+ try:
320
+ async with self.inference_lock:
321
+ await asyncio.get_event_loop().run_in_executor(
322
+ None, self._init_session, session
323
+ )
324
+
325
+ await ws.send_str(json.dumps({"type": "ready"}))
326
+ logger.debug(f"Client {session_id}: sent ready")
327
+
328
+ async for msg in ws:
329
+ if msg.type == WSMsgType.BINARY:
330
+ await self._handle_audio(session, msg.data)
331
+ elif msg.type == WSMsgType.TEXT:
332
+ try:
333
+ data = json.loads(msg.data)
334
+ msg_type = data.get("type")
335
+
336
+ if msg_type == "reset" or msg_type == "end":
337
+ finalize = data.get("finalize", True)
338
+ await self._reset_session(session, finalize=finalize)
339
+ else:
340
+ logger.warning(f"Client {session_id}: unknown message type: {msg_type}")
341
+
342
+ except json.JSONDecodeError:
343
+ logger.warning(f"Client {session_id}: invalid JSON")
344
+ elif msg.type == WSMsgType.ERROR:
345
+ logger.error(f"Client {session_id} WebSocket error: {ws.exception()}")
346
+ break
347
+
348
+ logger.info(f"Client {session_id} disconnected")
349
+
350
+ except Exception as e:
351
+ logger.error(f"Client {session_id} error: {e}")
352
+ import traceback
353
+ logger.error(traceback.format_exc())
354
+ try:
355
+ await ws.send_str(json.dumps({
356
+ "type": "error",
357
+ "message": str(e)
358
+ }))
359
+ except:
360
+ pass
361
+ finally:
362
+ if session_id in self.sessions:
363
+ del self.sessions[session_id]
364
+
365
+ return ws
366
+
367
+ async def _handle_audio(self, session: ASRSession, audio_bytes: bytes):
368
+ """Accumulate audio and process when enough frames available."""
369
+ audio_np = np.frombuffer(audio_bytes, dtype=np.int16).astype(np.float32) / 32768.0
370
+
371
+ if DEBUG_ASR:
372
+ chunk_hash = hashlib.md5(audio_bytes).hexdigest()[:8]
373
+ logger.debug(f"Session {session.id}: recv chunk {len(audio_bytes)}B hash={chunk_hash}")
374
+
375
+ session.accumulated_audio = np.concatenate([session.accumulated_audio, audio_np])
376
+
377
+ # Process if we have enough audio for new frames
378
+ min_audio_for_chunk = (session.emitted_frames + self.shift_frames + 1) * self.hop_samples
379
+
380
+ while len(session.accumulated_audio) >= min_audio_for_chunk:
381
+ async with self.inference_lock:
382
+ result = await asyncio.get_event_loop().run_in_executor(
383
+ None, self._process_chunk, session
384
+ )
385
+
386
+ if result is not None:
387
+ text, timestamps = result
388
+ if text is not None and text != session.current_text:
389
+ session.current_text = text
390
+ session.current_timestamps = timestamps
391
+ logger.debug(f"Session {session.id} interim: {text[-50:] if len(text) > 50 else text}")
392
+
393
+ formatted_timestamps = []
394
+ if timestamps:
395
+ if isinstance(timestamps, dict):
396
+ for key, val in timestamps.items():
397
+ if key != 'timestep':
398
+ formatted_timestamps.append({key: normalize_timestamp_output(val)})
399
+ elif isinstance(timestamps, list):
400
+ # It might be a list of dictionaries if returned directly from Hypothesis
401
+ formatted_timestamps = timestamps
402
+
403
+ await session.websocket.send_str(json.dumps({
404
+ "type": "transcript",
405
+ "text": text,
406
+ "timestamps": formatted_timestamps if formatted_timestamps else None,
407
+ "is_final": False
408
+ }))
409
+
410
+ # Update minimum for next iteration
411
+ min_audio_for_chunk = (session.emitted_frames + self.shift_frames + 1) * self.hop_samples
412
+
413
+ def _decode_stream_output(self, session, pred_out_stream):
414
+ """Manually decode model outputs to retrieve timestamps."""
415
+ # For RNNT models
416
+ if hasattr(self.model, 'joint'):
417
+ decoding = self.model.decoding
418
+ transcribed_texts = []
419
+ for preds_idx, preds_concat in enumerate(pred_out_stream):
420
+ # We need to reshape for RNNT decoder which expects [B, D] or [B, T, D]
421
+ # preds_concat is usually [T, D] from streaming step
422
+ if preds_concat.dim() == 2:
423
+ preds_tensor = preds_concat.unsqueeze(0) # [1, T, D]
424
+ else:
425
+ preds_tensor = preds_concat
426
+
427
+ encoded_len = torch.tensor([preds_tensor.size(1)], device=preds_tensor.device)
428
+
429
+ # We must use decoding() directly instead of rnnt_decoder_predictions_tensor
430
+ # so that hypothesis is correctly initialized with alignments before calling compute_rnnt_timestamps
431
+ hypotheses_list = decoding(
432
+ encoder_output=preds_tensor,
433
+ encoded_lengths=encoded_len,
434
+ partial_hypotheses=session.previous_hypotheses
435
+ )
436
+
437
+ # decoding() returns a tuple where [0] is a list of hypotheses
438
+ hypotheses_list = hypotheses_list[0]
439
+
440
+ if isinstance(hypotheses_list[0], list):
441
+ transcribed_texts.append(hypotheses_list[0][0])
442
+ else:
443
+ transcribed_texts.append(hypotheses_list[0])
444
+ # For CTC models
445
+ else:
446
+ if hasattr(self.model, 'ctc_decoder'):
447
+ decoding = self.model.ctc_decoding
448
+ else:
449
+ decoding = self.model.decoding
450
+
451
+ transcribed_texts = []
452
+ for preds_idx, preds_concat in enumerate(pred_out_stream):
453
+ encoded_len = torch.tensor([len(preds_concat)], device=preds_concat.device)
454
+ decoded_out = decoding.ctc_decoder_predictions_tensor(
455
+ decoder_outputs=preds_concat.unsqueeze(0),
456
+ decoder_lengths=encoded_len,
457
+ return_hypotheses=True,
458
+ )
459
+ if isinstance(decoded_out[0], list):
460
+ transcribed_texts.append(decoded_out[0][0])
461
+ else:
462
+ transcribed_texts.append(decoded_out[0])
463
+
464
+ # process timestamps
465
+ if hasattr(self.model.cfg, 'preprocessor'):
466
+ window_stride = self.model.cfg.preprocessor.get('window_stride', 0.01)
467
+ else:
468
+ window_stride = 0.01
469
+
470
+ subsampling_factor = 1
471
+ if hasattr(self.model, 'encoder') and hasattr(self.model.encoder, 'subsampling_factor'):
472
+ subsampling_factor = self.model.encoder.subsampling_factor
473
+ elif hasattr(self.model, 'encoder') and hasattr(self.model.encoder, 'conv_subsampling_factor'):
474
+ subsampling_factor = self.model.encoder.conv_subsampling_factor
475
+
476
+ # RNNT model returns a tuple of lists containing hypotheses when using decoding() directly
477
+ # We need to process the timestamps if they haven't been computed inside decoding()
478
+ if hasattr(self.model, 'joint'):
479
+ import copy
480
+ timestamp_type = 'all'
481
+ if hasattr(decoding, 'cfg'):
482
+ timestamp_type = decoding.cfg.get('rnnt_timestamp_type', 'all')
483
+
484
+ for i in range(len(transcribed_texts)):
485
+ if hasattr(transcribed_texts[i], 'timestamp') and not transcribed_texts[i].timestamp:
486
+ # Before computing timestamps, ensure the Hypothesis text contains the temporary storage
487
+ # format required by `compute_rnnt_timestamps`
488
+ if hasattr(transcribed_texts[i], 'y_sequence'):
489
+ prediction = transcribed_texts[i].y_sequence
490
+ if type(prediction) != list:
491
+ prediction = prediction.tolist()
492
+
493
+ # Remove any blank and possibly big blank tokens from prediction
494
+ if decoding.big_blank_durations is not None and decoding.big_blank_durations != []: # multi-blank RNNT
495
+ num_extra_outputs = len(decoding.big_blank_durations)
496
+ prediction = [p for p in prediction if p < decoding.blank_id - num_extra_outputs]
497
+ elif hasattr(decoding, '_is_tdt') and decoding._is_tdt: # TDT model.
498
+ prediction = [p for p in prediction if p < decoding.blank_id]
499
+ else: # standard RNN-T
500
+ prediction = [p for p in prediction if p != decoding.blank_id]
501
+
502
+ alignments = copy.deepcopy(transcribed_texts[i].alignments)
503
+ token_repetitions = [1] * len(alignments)
504
+
505
+ # Update hypothesis text to hold the tuple (prediction, alignments, token_repetitions)
506
+ transcribed_texts[i].text = (prediction, alignments, token_repetitions)
507
+
508
+ # Now compute the timestamps
509
+ transcribed_texts[i] = decoding.compute_rnnt_timestamps(transcribed_texts[i], timestamp_type)
510
+
511
+ process_timestamp_outputs(transcribed_texts, subsampling_factor=subsampling_factor, window_stride=window_stride)
512
+ return transcribed_texts
513
+
514
+ def _process_chunk(self, session: ASRSession) -> Optional[Tuple[str, Optional[dict]]]:
515
+ """Process accumulated audio, extract new mel frames, run streaming inference."""
516
+ try:
517
+ # Preprocess ALL accumulated audio
518
+ audio_tensor = torch.from_numpy(session.accumulated_audio).unsqueeze(0).cuda()
519
+ audio_len = torch.tensor([len(session.accumulated_audio)], device='cuda')
520
+
521
+ with torch.inference_mode():
522
+ mel, mel_len = self.model.preprocessor(
523
+ input_signal=audio_tensor,
524
+ length=audio_len
525
+ )
526
+
527
+ # Available frames (excluding last edge frame)
528
+ available_frames = mel.shape[-1] - 1
529
+ new_frame_count = available_frames - session.emitted_frames
530
+
531
+ if new_frame_count < self.shift_frames:
532
+ return session.current_text, session.current_timestamps # Not enough new frames
533
+
534
+ # Extract chunk with pre-encode cache
535
+ if session.emitted_frames == 0:
536
+ chunk_start = 0
537
+ chunk_end = self.shift_frames
538
+ drop_extra = 0
539
+ else:
540
+ chunk_start = session.emitted_frames - self.pre_encode_cache_size
541
+ chunk_end = session.emitted_frames + self.shift_frames
542
+ drop_extra = self.drop_extra
543
+
544
+ chunk_mel = mel[:, :, chunk_start:chunk_end]
545
+ chunk_len = torch.tensor([chunk_mel.shape[-1]], device='cuda')
546
+
547
+ # Run streaming inference
548
+ (
549
+ session.pred_out_stream,
550
+ transcribed_texts,
551
+ session.cache_last_channel,
552
+ session.cache_last_time,
553
+ session.cache_last_channel_len,
554
+ session.previous_hypotheses,
555
+ ) = self.model.conformer_stream_step(
556
+ processed_signal=chunk_mel,
557
+ processed_signal_length=chunk_len,
558
+ cache_last_channel=session.cache_last_channel,
559
+ cache_last_time=session.cache_last_time,
560
+ cache_last_channel_len=session.cache_last_channel_len,
561
+ keep_all_outputs=False,
562
+ previous_hypotheses=session.previous_hypotheses,
563
+ previous_pred_out=session.pred_out_stream,
564
+ drop_extra_pre_encoded=drop_extra,
565
+ return_transcription=True,
566
+ )
567
+
568
+ # Update emitted frame count
569
+ session.emitted_frames += self.shift_frames
570
+
571
+ # For RNNT models, conformer_stream_step already returns the decoded hypotheses in `transcribed_texts`
572
+ # (which is assigned to `best_hyp` inside the method). So we do not need to call _decode_stream_output manually.
573
+ # For CTC models, if we want full hypotheses with timestamps, we still need to decode manually.
574
+ if hasattr(self.model, 'joint'):
575
+ # The hypotheses are directly returned in `transcribed_texts`
576
+ pass
577
+ else:
578
+ transcribed_texts = self._decode_stream_output(session, session.pred_out_stream)
579
+
580
+ if transcribed_texts and transcribed_texts[0]:
581
+ hyp = transcribed_texts[0]
582
+ text = hyp.text if hasattr(hyp, 'text') else str(hyp)
583
+ timestamps = hyp.timestamp if hasattr(hyp, 'timestamp') else None
584
+ return text, timestamps
585
+
586
+ return session.current_text, session.current_timestamps
587
+
588
+ except Exception as e:
589
+ logger.error(f"Session {session.id} chunk processing error: {e}")
590
+ import traceback
591
+ logger.error(traceback.format_exc())
592
+ return None
593
+
594
+ async def _reset_session(self, session: ASRSession, finalize: bool = True):
595
+ """Handle reset with soft or hard finalization."""
596
+ import time
597
+
598
+ # Log audio state at reset for diagnostics
599
+ audio_samples = len(session.accumulated_audio) if session.accumulated_audio is not None else 0
600
+ audio_duration_ms = (audio_samples * 1000) // self.sample_rate
601
+ logger.debug(
602
+ f"Session {session.id} {'hard' if finalize else 'soft'} reset: "
603
+ f"accumulated={audio_samples} samples ({audio_duration_ms}ms), "
604
+ f"emitted={session.emitted_frames} frames"
605
+ )
606
+
607
+ if not finalize:
608
+ text = session.current_text
609
+ timestamps = session.current_timestamps
610
+
611
+ formatted_timestamps = []
612
+ if timestamps:
613
+ if isinstance(timestamps, dict):
614
+ for key, val in timestamps.items():
615
+ if key != 'timestep':
616
+ formatted_timestamps.append({key: normalize_timestamp_output(val)})
617
+ elif isinstance(timestamps, list):
618
+ formatted_timestamps = timestamps
619
+
620
+ await session.websocket.send_str(json.dumps({
621
+ "type": "transcript",
622
+ "text": text,
623
+ "timestamps": formatted_timestamps if formatted_timestamps else None,
624
+ "is_final": True,
625
+ "finalize": False
626
+ }))
627
+
628
+ logger.debug(f"Session {session.id} soft reset: '{text[-50:] if len(text) > 50 else text}'")
629
+ return
630
+
631
+ # HARD RESET: Full finalization with padding
632
+ original_audio_length = len(session.accumulated_audio) if session.accumulated_audio is not None else 0
633
+
634
+ if original_audio_length > 0:
635
+ padding_samples = self.final_padding_frames * self.hop_samples
636
+ silence_padding = np.zeros(padding_samples, dtype=np.float32)
637
+ session.accumulated_audio = np.concatenate([session.accumulated_audio, silence_padding])
638
+
639
+ # Process all remaining audio with keep_all_outputs=True
640
+ final_text = session.current_text
641
+ final_timestamps = session.current_timestamps
642
+ if session.accumulated_audio is not None and len(session.accumulated_audio) > 0:
643
+ start_time = time.perf_counter()
644
+ async with self.inference_lock:
645
+ result = await asyncio.get_event_loop().run_in_executor(
646
+ None, self._process_final_chunk, session
647
+ )
648
+ if result is not None:
649
+ final_text, final_timestamps = result
650
+ session.current_text = final_text
651
+ session.current_timestamps = final_timestamps
652
+ elapsed_ms = (time.perf_counter() - start_time) * 1000
653
+ logger.debug(f"Session {session.id} final chunk processed in {elapsed_ms:.1f}ms: '{final_text[-50:] if len(final_text) > 50 else final_text}'")
654
+
655
+ # Server-side deduplication: only send the delta (new portion)
656
+ if final_text.startswith(session.last_emitted_text):
657
+ delta_text = final_text[len(session.last_emitted_text):].lstrip()
658
+ else:
659
+ delta_text = final_text
660
+
661
+ session.last_emitted_text = final_text
662
+
663
+ formatted_timestamps = []
664
+ if final_timestamps:
665
+ if isinstance(final_timestamps, dict):
666
+ for key, val in final_timestamps.items():
667
+ if key != 'timestep':
668
+ formatted_timestamps.append({key: normalize_timestamp_output(val)})
669
+ elif isinstance(final_timestamps, list):
670
+ formatted_timestamps = final_timestamps
671
+
672
+ # Send only the delta to client
673
+ await session.websocket.send_str(json.dumps({
674
+ "type": "transcript",
675
+ "text": delta_text,
676
+ "timestamps": formatted_timestamps if formatted_timestamps else None,
677
+ "is_final": True,
678
+ "finalize": True
679
+ }))
680
+
681
+ session.last_emitted_text = ""
682
+ session.overlap_buffer = None
683
+ self._init_session(session)
684
+
685
+ def _process_final_chunk(self, session: ASRSession) -> Optional[Tuple[str, Optional[dict]]]:
686
+ """Process all remaining audio with keep_all_outputs=True."""
687
+ try:
688
+ if len(session.accumulated_audio) == 0:
689
+ return session.current_text, session.current_timestamps
690
+
691
+ # Preprocess ALL accumulated audio
692
+ audio_tensor = torch.from_numpy(session.accumulated_audio).unsqueeze(0).cuda()
693
+ audio_len = torch.tensor([len(session.accumulated_audio)], device='cuda')
694
+
695
+ with torch.inference_mode():
696
+ mel, mel_len = self.model.preprocessor(
697
+ input_signal=audio_tensor,
698
+ length=audio_len
699
+ )
700
+
701
+ # For final chunk, use ALL remaining frames (including edge)
702
+ total_mel_frames = mel.shape[-1]
703
+ remaining_frames = total_mel_frames - session.emitted_frames
704
+
705
+ if remaining_frames <= 0:
706
+ return session.current_text, session.current_timestamps
707
+
708
+ # Extract final chunk with pre-encode cache
709
+ if session.emitted_frames == 0:
710
+ chunk_start = 0
711
+ drop_extra = 0
712
+ else:
713
+ chunk_start = session.emitted_frames - self.pre_encode_cache_size
714
+ drop_extra = self.drop_extra
715
+
716
+ chunk_mel = mel[:, :, chunk_start:]
717
+ chunk_len = torch.tensor([chunk_mel.shape[-1]], device='cuda')
718
+
719
+ (
720
+ session.pred_out_stream,
721
+ transcribed_texts,
722
+ session.cache_last_channel,
723
+ session.cache_last_time,
724
+ session.cache_last_channel_len,
725
+ session.previous_hypotheses,
726
+ ) = self.model.conformer_stream_step(
727
+ processed_signal=chunk_mel,
728
+ processed_signal_length=chunk_len,
729
+ cache_last_channel=session.cache_last_channel,
730
+ cache_last_time=session.cache_last_time,
731
+ cache_last_channel_len=session.cache_last_channel_len,
732
+ keep_all_outputs=True, # Final chunk - output all remaining
733
+ previous_hypotheses=session.previous_hypotheses,
734
+ previous_pred_out=session.pred_out_stream,
735
+ drop_extra_pre_encoded=drop_extra,
736
+ return_transcription=True,
737
+ )
738
+
739
+ if hasattr(self.model, 'joint'):
740
+ pass
741
+ else:
742
+ transcribed_texts = self._decode_stream_output(session, session.pred_out_stream)
743
+
744
+ if transcribed_texts and transcribed_texts[0]:
745
+ hyp = transcribed_texts[0]
746
+ text = hyp.text if hasattr(hyp, 'text') else str(hyp)
747
+ timestamps = hyp.timestamp if hasattr(hyp, 'timestamp') else None
748
+ return text, timestamps
749
+
750
+ return session.current_text, session.current_timestamps
751
+
752
+ except Exception as e:
753
+ logger.error(f"Session {session.id} final chunk error: {e}")
754
+ import traceback
755
+ logger.error(traceback.format_exc())
756
+ return None
757
+
758
+ async def health_handler(self, request: web.Request) -> web.Response:
759
+ """Health check endpoint."""
760
+ return web.json_response({
761
+ "status": "healthy" if self.model_loaded else "loading",
762
+ "model_loaded": self.model_loaded,
763
+ })
764
+
765
+ async def start(self):
766
+ """Start the HTTP + WebSocket server."""
767
+ self.load_model()
768
+ self.model_loaded = True
769
+
770
+ logger.info(f"Starting streaming ASR server on ws://{self.host}:{self.port}")
771
+
772
+ app = web.Application()
773
+ app.router.add_get("/health", self.health_handler)
774
+ app.router.add_get("/", self.websocket_handler)
775
+
776
+ runner = web.AppRunner(app)
777
+ await runner.setup()
778
+ site = web.TCPSite(runner, self.host, self.port)
779
+ await site.start()
780
+
781
+ logger.info(f"ASR server listening on ws://{self.host}:{self.port}")
782
+ logger.info(f"Health check available at http://{self.host}:{self.port}/health")
783
+ await asyncio.Future() # Run forever
784
+
785
+
786
+ def main():
787
+ parser = argparse.ArgumentParser(description="Nemotron Streaming ASR WebSocket Server")
788
+ parser.add_argument("--host", default="0.0.0.0", help="Host to bind to")
789
+ parser.add_argument("--port", type=int, default=8080, help="Port to bind to")
790
+ parser.add_argument(
791
+ "--model",
792
+ default=DEFAULT_MODEL,
793
+ help="HuggingFace model name or path to local .nemo file"
794
+ )
795
+ parser.add_argument(
796
+ "--right-context",
797
+ type=int,
798
+ default=1,
799
+ choices=[0, 1, 6, 13],
800
+ help="Right context frames: 0=80ms, 1=160ms, 6=560ms, 13=1.12s latency"
801
+ )
802
+ args = parser.parse_args()
803
+
804
+ server = ASRServer(
805
+ model=args.model,
806
+ host=args.host,
807
+ port=args.port,
808
+ right_context=args.right_context,
809
+ )
810
+
811
+ asyncio.run(server.start())
812
+
813
+
814
+ if __name__ == "__main__":
815
+ main()
test_websocket_client.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Test WebSocket client for streaming ASR server."""
3
+
4
+ import asyncio
5
+ import json
6
+ import sys
7
+ import time
8
+ import wave
9
+
10
+ import websockets
11
+
12
+
13
+ async def test_asr_streaming(
14
+ audio_path: str,
15
+ server_url: str = "ws://localhost:8080",
16
+ chunk_ms: int = 500,
17
+ ):
18
+ """Send audio file to streaming ASR server and show interim results."""
19
+
20
+ print(f"Reading audio file: {audio_path}")
21
+
22
+ # Read WAV file
23
+ with wave.open(audio_path, 'rb') as wf:
24
+ sample_rate = wf.getframerate()
25
+ n_channels = wf.getnchannels()
26
+ sample_width = wf.getsampwidth()
27
+ n_frames = wf.getnframes()
28
+ audio_data = wf.readframes(n_frames)
29
+
30
+ duration = n_frames / sample_rate
31
+ print(f" Sample rate: {sample_rate} Hz")
32
+ print(f" Channels: {n_channels}")
33
+ print(f" Duration: {duration:.2f}s")
34
+ print(f" Size: {len(audio_data)} bytes")
35
+
36
+ # Calculate chunk size in bytes (16kHz, 16-bit = 2 bytes/sample)
37
+ chunk_samples = int(sample_rate * chunk_ms / 1000)
38
+ chunk_bytes = chunk_samples * sample_width # sample_width = 2 for 16-bit
39
+
40
+ print(f"\nChunk size: {chunk_ms}ms = {chunk_samples} samples = {chunk_bytes} bytes")
41
+ print(f"Connecting to {server_url}...")
42
+
43
+ start_time = time.time()
44
+
45
+ async with websockets.connect(server_url) as ws:
46
+ connect_time = time.time()
47
+ print(f" Connected in {(connect_time - start_time)*1000:.0f}ms")
48
+
49
+ # Wait for ready message
50
+ ready_msg = await ws.recv()
51
+ ready_data = json.loads(ready_msg)
52
+ if ready_data.get("type") != "ready":
53
+ print(f" WARNING: Expected 'ready', got: {ready_data}")
54
+ else:
55
+ print(f" Server ready")
56
+
57
+ ready_time = time.time()
58
+
59
+ # Track interim results
60
+ interim_count = 0
61
+ last_interim = ""
62
+
63
+ # Create a task to receive messages
64
+ async def receive_messages():
65
+ nonlocal interim_count, last_interim
66
+ try:
67
+ async for message in ws:
68
+ data = json.loads(message)
69
+ if data.get("type") == "transcript":
70
+ text = data.get("text", "")
71
+ is_final = data.get("is_final", False)
72
+
73
+ if is_final:
74
+ return text
75
+ else:
76
+ interim_count += 1
77
+ last_interim = text
78
+ # Show interim result (truncated)
79
+ display = text[:60] + "..." if len(text) > 60 else text
80
+ print(f" [interim {interim_count}] {display}")
81
+ elif data.get("type") == "error":
82
+ print(f" ERROR: {data.get('message')}")
83
+ return None
84
+ except websockets.exceptions.ConnectionClosed:
85
+ return last_interim
86
+
87
+ # Start receiving in background
88
+ receive_task = asyncio.create_task(receive_messages())
89
+
90
+ # Send audio data in chunks
91
+ total_sent = 0
92
+ chunks_sent = 0
93
+
94
+ print(f"\nSending audio in {chunk_ms}ms chunks...")
95
+ send_start = time.time()
96
+
97
+ for i in range(0, len(audio_data), chunk_bytes):
98
+ chunk = audio_data[i:i+chunk_bytes]
99
+ await ws.send(chunk)
100
+ total_sent += len(chunk)
101
+ chunks_sent += 1
102
+
103
+ # Simulate real-time streaming
104
+ await asyncio.sleep(chunk_ms / 1000)
105
+
106
+ send_time = time.time()
107
+ print(f" Sent {chunks_sent} chunks ({total_sent} bytes) in {(send_time - send_start)*1000:.0f}ms")
108
+
109
+ # Record time of last audio chunk sent
110
+ last_audio_time = send_time
111
+
112
+ # Signal end of audio
113
+ end_signal_time = time.time()
114
+ await ws.send(json.dumps({"type": "reset"}))
115
+
116
+ # Wait for final transcript
117
+ print("\nWaiting for final transcript...")
118
+ transcript = await receive_task
119
+ final_recv_time = time.time()
120
+
121
+ # Calculate time-to-final-transcription
122
+ time_to_final = (final_recv_time - last_audio_time) * 1000
123
+ end_signal_to_final = (final_recv_time - end_signal_time) * 1000
124
+
125
+ print(f"\n{'='*60}")
126
+ print("FINAL TRANSCRIPT:")
127
+ print(f"{'='*60}")
128
+ print(transcript if transcript else "(empty)")
129
+ print(f"{'='*60}")
130
+
131
+ total_time = final_recv_time - start_time
132
+ print(f"\nStatistics:")
133
+ print(f" Interim results: {interim_count}")
134
+ print(f" Total time: {total_time*1000:.0f}ms")
135
+ print(f" Audio duration: {duration:.2f}s")
136
+ print(f" Real-time factor: {total_time/duration:.2f}x")
137
+ print(f"\nFinalization latency:")
138
+ print(f" Last audio chunk -> final transcript: {time_to_final:.0f}ms")
139
+ print(f" End signal -> final transcript: {end_signal_to_final:.0f}ms")
140
+
141
+ return transcript
142
+
143
+
144
+ async def test_multiple_chunk_sizes(audio_path: str, server_url: str):
145
+ """Test with different chunk sizes."""
146
+ print("=" * 60)
147
+ print("Testing Multiple Chunk Sizes")
148
+ print("=" * 60)
149
+
150
+ for chunk_ms in [500, 160, 80]:
151
+ print(f"\n{'='*60}")
152
+ print(f"CHUNK SIZE: {chunk_ms}ms")
153
+ print(f"{'='*60}")
154
+
155
+ try:
156
+ await test_asr_streaming(audio_path, server_url, chunk_ms)
157
+ except Exception as e:
158
+ print(f"ERROR with {chunk_ms}ms chunks: {e}")
159
+
160
+ # Small delay between tests
161
+ await asyncio.sleep(1)
162
+
163
+
164
+ if __name__ == "__main__":
165
+
166
+ import sys
167
+ # sys.argv.append( '--all' )
168
+
169
+ audio_path = "./harvard_16k.wav"
170
+ server_url = "ws://127.0.0.1:8080"
171
+
172
+ # Check for --all flag to test all chunk sizes
173
+ if "--all" in sys.argv:
174
+ asyncio.run(test_multiple_chunk_sizes(audio_path, server_url))
175
+ else:
176
+ chunk_ms = 500
177
+ if "--chunk" in sys.argv:
178
+ idx = sys.argv.index("--chunk")
179
+ if idx + 1 < len(sys.argv):
180
+ chunk_ms = int(sys.argv[idx + 1])
181
+
182
+ asyncio.run(test_asr_streaming(audio_path, server_url, chunk_ms))