dlxj commited on
Commit ·
7a12a78
1
Parent(s): 66ba09a
add server_aware_streaming.py 成功推理 RNNT 的 nemotron-speech-streaming-en-0.6b ,理论上同时兼容 CTC
Browse filesFiles changed (2)
- server_aware_streaming.pyAdded+815
- test_websocket_client.pyAdded+182
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815"""WebSocket ASR server for Nemotron-Speech with true incremental streaming and timestamps."""
import asyncioimport argparseimport hashlibimport jsonimport osfrom dataclasses import dataclass, fieldfrom typing import Any, Optional, Tuple
import numpy as npimport torchfrom aiohttp import web, WSMsgTypefrom loguru import logger
from nemo.collections.asr.parts.utils.transcribe_utils import normalize_timestamp_output, process_timestamp_outputs
# Enable debug logging with DEBUG_ASR=1DEBUG_ASR = os.environ.get("DEBUG_ASR", "0") == "1"
def _hash_audio(audio: np.ndarray) -> str: """Get short hash of audio array for debugging.""" if audio is None or len(audio) == 0: return "empty" return hashlib.md5(audio.tobytes()).hexdigest()[:8]
DEFAULT_MODEL = "./nemotron-speech-streaming-en-0.6b/nemotron-speech-streaming-en-0.6b.nemo"# DEFAULT_MODEL = "results/NeMo_Ja_FastConformer_Streaming/checkpoints/NeMo_Ja_FastConformer_Streaming.nemo"
# Right context options for att_context_size=[70, X]RIGHT_CONTEXT_OPTIONS = { 0: "~80ms ultra-low latency", 1: "~160ms low latency (recommended)", 6: "~560ms balanced", 13: "~1.12s highest accuracy",}
@dataclassclass ASRSession: """Per-connection session state with caches for true incremental streaming."""
id: str websocket: Any
# Accumulated audio buffer (all audio received so far) accumulated_audio: Optional[np.ndarray] = None
# Number of mel frames already emitted to encoder emitted_frames: int = 0
# Encoder cache state cache_last_channel: Optional[torch.Tensor] = None cache_last_time: Optional[torch.Tensor] = None cache_last_channel_len: Optional[torch.Tensor] = None
# Decoder state previous_hypotheses: Any = None pred_out_stream: Any = None
# Current transcription (model's cumulative output) current_text: str = "" # Current timestamps current_timestamps: Optional[dict] = None
# Last text emitted to client on hard reset (for server-side deduplication) # We only send the delta (new portion) to avoid downstream duplication last_emitted_text: str = ""
# Audio overlap buffer for mid-utterance reset continuity # This preserves the last N ms of audio to provide encoder left-context # when a new segment starts after a reset overlap_buffer: Optional[np.ndarray] = None
class ASRServer: """WebSocket server for streaming ASR with true incremental processing."""
def __init__( self, model: str, host: str = "0.0.0.0", port: int = 8080, right_context: int = 1, ): self.model_name_or_path = model self.host = host self.port = port self.right_context = right_context self.model = None self.sample_rate = 16000
# Inference lock self.inference_lock = asyncio.Lock()
# Active sessions self.sessions: dict[str, ASRSession] = {}
# Model loaded flag for health check self.model_loaded = False
# Streaming parameters (calculated from model config) self.shift_frames = None self.pre_encode_cache_size = None self.hop_samples = None
# Audio overlap for mid-utterance reset continuity (calculated in load_model) self.overlap_samples = None
def load_model(self): """Load the NeMo ASR model with streaming configuration.""" import nemo.collections.asr as nemo_asr from omegaconf import OmegaConf
# Detect if model is a local .nemo file or HuggingFace model name is_local_file = ( self.model_name_or_path.endswith('.nemo') or os.path.exists(self.model_name_or_path) )
if is_local_file: logger.info(f"Loading model from local file: {self.model_name_or_path}") self.model = nemo_asr.models.ASRModel.restore_from( self.model_name_or_path, map_location='cpu' ) else: logger.info(f"Loading model from HuggingFace: {self.model_name_or_path}") self.model = nemo_asr.models.ASRModel.from_pretrained( self.model_name_or_path, map_location='cpu' ) self.model = self.model.cuda()
# Configure attention context for streaming logger.info(f"Setting att_context_size=[70, {self.right_context}] ({RIGHT_CONTEXT_OPTIONS.get(self.right_context, 'custom')})") if hasattr(self.model.encoder, "set_default_att_context_size"): self.model.encoder.set_default_att_context_size([70, self.right_context])
# Configure greedy decoding (required for Blackwell GPU) logger.info("Configuring greedy decoding for Blackwell compatibility and enabling timestamps...") # Check model type to set preserve_alignments preserve_alignments = False if hasattr(self.model, 'joint'): # RNNT model preserve_alignments = True decoding_cfg_dict = { 'strategy': 'greedy', 'greedy': { 'max_symbols': 10, 'loop_labels': False, 'use_cuda_graph_decoder': False, }, 'compute_timestamps': True } if preserve_alignments: decoding_cfg_dict['preserve_alignments'] = True self.model.change_decoding_strategy( decoding_cfg=OmegaConf.create(decoding_cfg_dict) ) # Force enable timestamps if hasattr(self.model, 'decoding'): if hasattr(self.model.decoding, 'compute_timestamps'): self.model.decoding.compute_timestamps = True if hasattr(self.model.decoding, 'preserve_alignments'): self.model.decoding.preserve_alignments = preserve_alignments if hasattr(self.model.decoding, 'ctc_decoder') and hasattr(self.model.decoding.ctc_decoder, 'compute_timestamps'): self.model.decoding.ctc_decoder.compute_timestamps = True self.model.decoding.ctc_decoder.return_hypotheses = True # Force RNNT decoder settings if present if hasattr(self.model, 'joint'): if hasattr(self.model.decoding, 'rnnt_decoder_predictions_tensor'): if hasattr(self.model.decoding, 'compute_timestamps'): # We MUST set this to False during the stream step, # otherwise the internal `rnnt_decoder_predictions_tensor` will try to compute # timestamps on partial chunks and fail with length mismatch ValueError. # We will manually compute the timestamps later in `_process_chunk` / `_process_final_chunk` self.model.decoding.compute_timestamps = False if hasattr(self.model.decoding, 'preserve_alignments'): self.model.decoding.preserve_alignments = True if hasattr(self.model.decoding, 'return_hypotheses'): self.model.decoding.return_hypotheses = True self.model.eval()
# Disable dither for deterministic preprocessing self.model.preprocessor.featurizer.dither = 0.0
# Get streaming config scfg = self.model.encoder.streaming_cfg logger.info(f"Streaming config: chunk_size={scfg.chunk_size}, shift_size={scfg.shift_size}")
# Calculate parameters preprocessor_cfg = self.model.cfg.preprocessor hop_length_sec = preprocessor_cfg.get('window_stride', 0.01) self.hop_samples = int(hop_length_sec * self.sample_rate)
# shift_size[1] = 16 frames for 160ms chunks self.shift_frames = scfg.shift_size[1] if isinstance(scfg.shift_size, list) else scfg.shift_size
# pre_encode_cache_size[1] = 9 frames pre_cache = scfg.pre_encode_cache_size self.pre_encode_cache_size = pre_cache[1] if isinstance(pre_cache, list) else pre_cache
# drop_extra_pre_encoded for non-first chunks self.drop_extra = scfg.drop_extra_pre_encoded
# Calculate silence padding for final chunk: # - right_context chunks for encoder lookahead # - 1 additional chunk for decoder finalization # With right_context=1, this is (1+1)*160ms = 320ms self.final_padding_frames = (self.right_context + 1) * self.shift_frames padding_ms = self.final_padding_frames * hop_length_sec * 1000
# Calculate audio overlap for mid-utterance reset continuity # Use pre_encode_cache_size frames = 90ms of left-context # This allows the encoder to have proper context when starting a new segment self.overlap_samples = self.pre_encode_cache_size * self.hop_samples overlap_ms = self.overlap_samples * 1000 / self.sample_rate
shift_ms = self.shift_frames * hop_length_sec * 1000 logger.info(f"Model loaded: {type(self.model).__name__}") logger.info(f"Shift size: {shift_ms:.0f}ms ({self.shift_frames} frames)") logger.info(f"Pre-encode cache: {self.pre_encode_cache_size} frames") logger.info(f"Final chunk padding: {padding_ms:.0f}ms ({self.final_padding_frames} frames)") logger.info(f"Audio overlap for resets: {overlap_ms:.0f}ms ({self.overlap_samples} samples)")
# Warmup inference to ensure model is fully loaded on GPU # This prevents GPU memory issues when LLM starts later self._warmup()
def _warmup(self): """Run warmup inference using streaming API to claim GPU memory.""" import time
logger.info("Running warmup inference (streaming API) to claim GPU memory...") start = time.perf_counter()
# Generate 1 second of silence plus padding for warmup warmup_samples = self.sample_rate + (self.final_padding_frames * self.hop_samples) warmup_audio = np.zeros(warmup_samples, dtype=np.float32)
# Run streaming inference to force all CUDA kernels to compile with torch.inference_mode(): audio_tensor = torch.from_numpy(warmup_audio).unsqueeze(0).cuda() audio_len = torch.tensor([len(warmup_audio)], device='cuda')
# Preprocess mel, mel_len = self.model.preprocessor(input_signal=audio_tensor, length=audio_len)
# Get initial cache cache = self.model.encoder.get_initial_cache_state(batch_size=1)
# Run streaming step (processes entire mel as one chunk) _ = self.model.conformer_stream_step( processed_signal=mel, processed_signal_length=mel_len, cache_last_channel=cache[0], cache_last_time=cache[1], cache_last_channel_len=cache[2], keep_all_outputs=True, previous_hypotheses=None, previous_pred_out=None, drop_extra_pre_encoded=0, return_transcription=True, )
elapsed = (time.perf_counter() - start) * 1000 logger.info(f"Warmup complete in {elapsed:.0f}ms - GPU memory claimed")
def _init_session(self, session: ASRSession): """Initialize a fresh session.""" # Initialize encoder cache cache = self.model.encoder.get_initial_cache_state(batch_size=1) session.cache_last_channel = cache[0] session.cache_last_time = cache[1] session.cache_last_channel_len = cache[2]
# Reset audio buffer and frame counter if session.overlap_buffer is not None and len(session.overlap_buffer) > 0: session.accumulated_audio = session.overlap_buffer.copy() overlap_ms = len(session.overlap_buffer) * 1000 / self.sample_rate logger.debug( f"Session {session.id}: prepending {len(session.overlap_buffer)} samples " f"({overlap_ms:.0f}ms) of overlap audio" ) session.overlap_buffer = None # Clear after use else: session.accumulated_audio = np.array([], dtype=np.float32)
session.emitted_frames = 0
# Reset decoder state session.previous_hypotheses = None session.pred_out_stream = None session.current_text = "" session.current_timestamps = None
async def websocket_handler(self, request: web.Request) -> web.WebSocketResponse: """Handle a WebSocket client connection.""" import uuid
ws = web.WebSocketResponse(max_msg_size=10 * 1024 * 1024) await ws.prepare(request)
session_id = str(uuid.uuid4())[:8] session = ASRSession(id=session_id, websocket=ws) self.sessions[session_id] = session
logger.info(f"Client {session_id} connected")
try: async with self.inference_lock: await asyncio.get_event_loop().run_in_executor( None, self._init_session, session )
await ws.send_str(json.dumps({"type": "ready"})) logger.debug(f"Client {session_id}: sent ready")
async for msg in ws: if msg.type == WSMsgType.BINARY: await self._handle_audio(session, msg.data) elif msg.type == WSMsgType.TEXT: try: data = json.loads(msg.data) msg_type = data.get("type")
if msg_type == "reset" or msg_type == "end": finalize = data.get("finalize", True) await self._reset_session(session, finalize=finalize) else: logger.warning(f"Client {session_id}: unknown message type: {msg_type}")
except json.JSONDecodeError: logger.warning(f"Client {session_id}: invalid JSON") elif msg.type == WSMsgType.ERROR: logger.error(f"Client {session_id} WebSocket error: {ws.exception()}") break
logger.info(f"Client {session_id} disconnected")
except Exception as e: logger.error(f"Client {session_id} error: {e}") import traceback logger.error(traceback.format_exc()) try: await ws.send_str(json.dumps({ "type": "error", "message": str(e) })) except: pass finally: if session_id in self.sessions: del self.sessions[session_id]
return ws
async def _handle_audio(self, session: ASRSession, audio_bytes: bytes): """Accumulate audio and process when enough frames available.""" audio_np = np.frombuffer(audio_bytes, dtype=np.int16).astype(np.float32) / 32768.0
if DEBUG_ASR: chunk_hash = hashlib.md5(audio_bytes).hexdigest()[:8] logger.debug(f"Session {session.id}: recv chunk {len(audio_bytes)}B hash={chunk_hash}")
session.accumulated_audio = np.concatenate([session.accumulated_audio, audio_np])
# Process if we have enough audio for new frames min_audio_for_chunk = (session.emitted_frames + self.shift_frames + 1) * self.hop_samples
while len(session.accumulated_audio) >= min_audio_for_chunk: async with self.inference_lock: result = await asyncio.get_event_loop().run_in_executor( None, self._process_chunk, session )
if result is not None: text, timestamps = result if text is not None and text != session.current_text: session.current_text = text session.current_timestamps = timestamps logger.debug(f"Session {session.id} interim: {text[-50:] if len(text) > 50 else text}") formatted_timestamps = [] if timestamps: if isinstance(timestamps, dict): for key, val in timestamps.items(): if key != 'timestep': formatted_timestamps.append({key: normalize_timestamp_output(val)}) elif isinstance(timestamps, list): # It might be a list of dictionaries if returned directly from Hypothesis formatted_timestamps = timestamps await session.websocket.send_str(json.dumps({ "type": "transcript", "text": text, "timestamps": formatted_timestamps if formatted_timestamps else None, "is_final": False }))
# Update minimum for next iteration min_audio_for_chunk = (session.emitted_frames + self.shift_frames + 1) * self.hop_samples
def _decode_stream_output(self, session, pred_out_stream): """Manually decode model outputs to retrieve timestamps.""" # For RNNT models if hasattr(self.model, 'joint'): decoding = self.model.decoding transcribed_texts = [] for preds_idx, preds_concat in enumerate(pred_out_stream): # We need to reshape for RNNT decoder which expects [B, D] or [B, T, D] # preds_concat is usually [T, D] from streaming step if preds_concat.dim() == 2: preds_tensor = preds_concat.unsqueeze(0) # [1, T, D] else: preds_tensor = preds_concat encoded_len = torch.tensor([preds_tensor.size(1)], device=preds_tensor.device) # We must use decoding() directly instead of rnnt_decoder_predictions_tensor # so that hypothesis is correctly initialized with alignments before calling compute_rnnt_timestamps hypotheses_list = decoding( encoder_output=preds_tensor, encoded_lengths=encoded_len, partial_hypotheses=session.previous_hypotheses ) # decoding() returns a tuple where [0] is a list of hypotheses hypotheses_list = hypotheses_list[0] if isinstance(hypotheses_list[0], list): transcribed_texts.append(hypotheses_list[0][0]) else: transcribed_texts.append(hypotheses_list[0]) # For CTC models else: if hasattr(self.model, 'ctc_decoder'): decoding = self.model.ctc_decoding else: decoding = self.model.decoding transcribed_texts = [] for preds_idx, preds_concat in enumerate(pred_out_stream): encoded_len = torch.tensor([len(preds_concat)], device=preds_concat.device) decoded_out = decoding.ctc_decoder_predictions_tensor( decoder_outputs=preds_concat.unsqueeze(0), decoder_lengths=encoded_len, return_hypotheses=True, ) if isinstance(decoded_out[0], list): transcribed_texts.append(decoded_out[0][0]) else: transcribed_texts.append(decoded_out[0]) # process timestamps if hasattr(self.model.cfg, 'preprocessor'): window_stride = self.model.cfg.preprocessor.get('window_stride', 0.01) else: window_stride = 0.01 subsampling_factor = 1 if hasattr(self.model, 'encoder') and hasattr(self.model.encoder, 'subsampling_factor'): subsampling_factor = self.model.encoder.subsampling_factor elif hasattr(self.model, 'encoder') and hasattr(self.model.encoder, 'conv_subsampling_factor'): subsampling_factor = self.model.encoder.conv_subsampling_factor # RNNT model returns a tuple of lists containing hypotheses when using decoding() directly # We need to process the timestamps if they haven't been computed inside decoding() if hasattr(self.model, 'joint'): import copy timestamp_type = 'all' if hasattr(decoding, 'cfg'): timestamp_type = decoding.cfg.get('rnnt_timestamp_type', 'all') for i in range(len(transcribed_texts)): if hasattr(transcribed_texts[i], 'timestamp') and not transcribed_texts[i].timestamp: # Before computing timestamps, ensure the Hypothesis text contains the temporary storage # format required by `compute_rnnt_timestamps` if hasattr(transcribed_texts[i], 'y_sequence'): prediction = transcribed_texts[i].y_sequence if type(prediction) != list: prediction = prediction.tolist() # Remove any blank and possibly big blank tokens from prediction if decoding.big_blank_durations is not None and decoding.big_blank_durations != []: # multi-blank RNNT num_extra_outputs = len(decoding.big_blank_durations) prediction = [p for p in prediction if p < decoding.blank_id - num_extra_outputs] elif hasattr(decoding, '_is_tdt') and decoding._is_tdt: # TDT model. prediction = [p for p in prediction if p < decoding.blank_id] else: # standard RNN-T prediction = [p for p in prediction if p != decoding.blank_id] alignments = copy.deepcopy(transcribed_texts[i].alignments) token_repetitions = [1] * len(alignments) # Update hypothesis text to hold the tuple (prediction, alignments, token_repetitions) transcribed_texts[i].text = (prediction, alignments, token_repetitions) # Now compute the timestamps transcribed_texts[i] = decoding.compute_rnnt_timestamps(transcribed_texts[i], timestamp_type) process_timestamp_outputs(transcribed_texts, subsampling_factor=subsampling_factor, window_stride=window_stride) return transcribed_texts
def _process_chunk(self, session: ASRSession) -> Optional[Tuple[str, Optional[dict]]]: """Process accumulated audio, extract new mel frames, run streaming inference.""" try: # Preprocess ALL accumulated audio audio_tensor = torch.from_numpy(session.accumulated_audio).unsqueeze(0).cuda() audio_len = torch.tensor([len(session.accumulated_audio)], device='cuda')
with torch.inference_mode(): mel, mel_len = self.model.preprocessor( input_signal=audio_tensor, length=audio_len )
# Available frames (excluding last edge frame) available_frames = mel.shape[-1] - 1 new_frame_count = available_frames - session.emitted_frames
if new_frame_count < self.shift_frames: return session.current_text, session.current_timestamps # Not enough new frames
# Extract chunk with pre-encode cache if session.emitted_frames == 0: chunk_start = 0 chunk_end = self.shift_frames drop_extra = 0 else: chunk_start = session.emitted_frames - self.pre_encode_cache_size chunk_end = session.emitted_frames + self.shift_frames drop_extra = self.drop_extra
chunk_mel = mel[:, :, chunk_start:chunk_end] chunk_len = torch.tensor([chunk_mel.shape[-1]], device='cuda')
# Run streaming inference ( session.pred_out_stream, transcribed_texts, session.cache_last_channel, session.cache_last_time, session.cache_last_channel_len, session.previous_hypotheses, ) = self.model.conformer_stream_step( processed_signal=chunk_mel, processed_signal_length=chunk_len, cache_last_channel=session.cache_last_channel, cache_last_time=session.cache_last_time, cache_last_channel_len=session.cache_last_channel_len, keep_all_outputs=False, previous_hypotheses=session.previous_hypotheses, previous_pred_out=session.pred_out_stream, drop_extra_pre_encoded=drop_extra, return_transcription=True, )
# Update emitted frame count session.emitted_frames += self.shift_frames
# For RNNT models, conformer_stream_step already returns the decoded hypotheses in `transcribed_texts` # (which is assigned to `best_hyp` inside the method). So we do not need to call _decode_stream_output manually. # For CTC models, if we want full hypotheses with timestamps, we still need to decode manually. if hasattr(self.model, 'joint'): # The hypotheses are directly returned in `transcribed_texts` pass else: transcribed_texts = self._decode_stream_output(session, session.pred_out_stream) if transcribed_texts and transcribed_texts[0]: hyp = transcribed_texts[0] text = hyp.text if hasattr(hyp, 'text') else str(hyp) timestamps = hyp.timestamp if hasattr(hyp, 'timestamp') else None return text, timestamps
return session.current_text, session.current_timestamps
except Exception as e: logger.error(f"Session {session.id} chunk processing error: {e}") import traceback logger.error(traceback.format_exc()) return None
async def _reset_session(self, session: ASRSession, finalize: bool = True): """Handle reset with soft or hard finalization.""" import time
# Log audio state at reset for diagnostics audio_samples = len(session.accumulated_audio) if session.accumulated_audio is not None else 0 audio_duration_ms = (audio_samples * 1000) // self.sample_rate logger.debug( f"Session {session.id} {'hard' if finalize else 'soft'} reset: " f"accumulated={audio_samples} samples ({audio_duration_ms}ms), " f"emitted={session.emitted_frames} frames" )
if not finalize: text = session.current_text timestamps = session.current_timestamps formatted_timestamps = [] if timestamps: if isinstance(timestamps, dict): for key, val in timestamps.items(): if key != 'timestep': formatted_timestamps.append({key: normalize_timestamp_output(val)}) elif isinstance(timestamps, list): formatted_timestamps = timestamps
await session.websocket.send_str(json.dumps({ "type": "transcript", "text": text, "timestamps": formatted_timestamps if formatted_timestamps else None, "is_final": True, "finalize": False }))
logger.debug(f"Session {session.id} soft reset: '{text[-50:] if len(text) > 50 else text}'") return
# HARD RESET: Full finalization with padding original_audio_length = len(session.accumulated_audio) if session.accumulated_audio is not None else 0
if original_audio_length > 0: padding_samples = self.final_padding_frames * self.hop_samples silence_padding = np.zeros(padding_samples, dtype=np.float32) session.accumulated_audio = np.concatenate([session.accumulated_audio, silence_padding])
# Process all remaining audio with keep_all_outputs=True final_text = session.current_text final_timestamps = session.current_timestamps if session.accumulated_audio is not None and len(session.accumulated_audio) > 0: start_time = time.perf_counter() async with self.inference_lock: result = await asyncio.get_event_loop().run_in_executor( None, self._process_final_chunk, session ) if result is not None: final_text, final_timestamps = result session.current_text = final_text session.current_timestamps = final_timestamps elapsed_ms = (time.perf_counter() - start_time) * 1000 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}'")
# Server-side deduplication: only send the delta (new portion) if final_text.startswith(session.last_emitted_text): delta_text = final_text[len(session.last_emitted_text):].lstrip() else: delta_text = final_text
session.last_emitted_text = final_text formatted_timestamps = [] if final_timestamps: if isinstance(final_timestamps, dict): for key, val in final_timestamps.items(): if key != 'timestep': formatted_timestamps.append({key: normalize_timestamp_output(val)}) elif isinstance(final_timestamps, list): formatted_timestamps = final_timestamps
# Send only the delta to client await session.websocket.send_str(json.dumps({ "type": "transcript", "text": delta_text, "timestamps": formatted_timestamps if formatted_timestamps else None, "is_final": True, "finalize": True }))
session.last_emitted_text = "" session.overlap_buffer = None self._init_session(session)
def _process_final_chunk(self, session: ASRSession) -> Optional[Tuple[str, Optional[dict]]]: """Process all remaining audio with keep_all_outputs=True.""" try: if len(session.accumulated_audio) == 0: return session.current_text, session.current_timestamps
# Preprocess ALL accumulated audio audio_tensor = torch.from_numpy(session.accumulated_audio).unsqueeze(0).cuda() audio_len = torch.tensor([len(session.accumulated_audio)], device='cuda')
with torch.inference_mode(): mel, mel_len = self.model.preprocessor( input_signal=audio_tensor, length=audio_len )
# For final chunk, use ALL remaining frames (including edge) total_mel_frames = mel.shape[-1] remaining_frames = total_mel_frames - session.emitted_frames
if remaining_frames <= 0: return session.current_text, session.current_timestamps
# Extract final chunk with pre-encode cache if session.emitted_frames == 0: chunk_start = 0 drop_extra = 0 else: chunk_start = session.emitted_frames - self.pre_encode_cache_size drop_extra = self.drop_extra
chunk_mel = mel[:, :, chunk_start:] chunk_len = torch.tensor([chunk_mel.shape[-1]], device='cuda')
( session.pred_out_stream, transcribed_texts, session.cache_last_channel, session.cache_last_time, session.cache_last_channel_len, session.previous_hypotheses, ) = self.model.conformer_stream_step( processed_signal=chunk_mel, processed_signal_length=chunk_len, cache_last_channel=session.cache_last_channel, cache_last_time=session.cache_last_time, cache_last_channel_len=session.cache_last_channel_len, keep_all_outputs=True, # Final chunk - output all remaining previous_hypotheses=session.previous_hypotheses, previous_pred_out=session.pred_out_stream, drop_extra_pre_encoded=drop_extra, return_transcription=True, )
if hasattr(self.model, 'joint'): pass else: transcribed_texts = self._decode_stream_output(session, session.pred_out_stream) if transcribed_texts and transcribed_texts[0]: hyp = transcribed_texts[0] text = hyp.text if hasattr(hyp, 'text') else str(hyp) timestamps = hyp.timestamp if hasattr(hyp, 'timestamp') else None return text, timestamps
return session.current_text, session.current_timestamps
except Exception as e: logger.error(f"Session {session.id} final chunk error: {e}") import traceback logger.error(traceback.format_exc()) return None
async def health_handler(self, request: web.Request) -> web.Response: """Health check endpoint.""" return web.json_response({ "status": "healthy" if self.model_loaded else "loading", "model_loaded": self.model_loaded, })
async def start(self): """Start the HTTP + WebSocket server.""" self.load_model() self.model_loaded = True
logger.info(f"Starting streaming ASR server on ws://{self.host}:{self.port}")
app = web.Application() app.router.add_get("/health", self.health_handler) app.router.add_get("/", self.websocket_handler)
runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, self.host, self.port) await site.start()
logger.info(f"ASR server listening on ws://{self.host}:{self.port}") logger.info(f"Health check available at http://{self.host}:{self.port}/health") await asyncio.Future() # Run forever
def main(): parser = argparse.ArgumentParser(description="Nemotron Streaming ASR WebSocket Server") parser.add_argument("--host", default="0.0.0.0", help="Host to bind to") parser.add_argument("--port", type=int, default=8080, help="Port to bind to") parser.add_argument( "--model", default=DEFAULT_MODEL, help="HuggingFace model name or path to local .nemo file" ) parser.add_argument( "--right-context", type=int, default=1, choices=[0, 1, 6, 13], help="Right context frames: 0=80ms, 1=160ms, 6=560ms, 13=1.12s latency" ) args = parser.parse_args()
server = ASRServer( model=args.model, host=args.host, port=args.port, right_context=args.right_context, )
asyncio.run(server.start())
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182#!/usr/bin/env python3"""Test WebSocket client for streaming ASR server."""
import asyncioimport jsonimport sysimport timeimport wave
import websockets
async def test_asr_streaming( audio_path: str, server_url: str = "ws://localhost:8080", chunk_ms: int = 500,): """Send audio file to streaming ASR server and show interim results."""
print(f"Reading audio file: {audio_path}")
# Read WAV file with wave.open(audio_path, 'rb') as wf: sample_rate = wf.getframerate() n_channels = wf.getnchannels() sample_width = wf.getsampwidth() n_frames = wf.getnframes() audio_data = wf.readframes(n_frames)
duration = n_frames / sample_rate print(f" Sample rate: {sample_rate} Hz") print(f" Channels: {n_channels}") print(f" Duration: {duration:.2f}s") print(f" Size: {len(audio_data)} bytes")
# Calculate chunk size in bytes (16kHz, 16-bit = 2 bytes/sample) chunk_samples = int(sample_rate * chunk_ms / 1000) chunk_bytes = chunk_samples * sample_width # sample_width = 2 for 16-bit
print(f"\nChunk size: {chunk_ms}ms = {chunk_samples} samples = {chunk_bytes} bytes") print(f"Connecting to {server_url}...")
start_time = time.time()
async with websockets.connect(server_url) as ws: connect_time = time.time() print(f" Connected in {(connect_time - start_time)*1000:.0f}ms")
# Wait for ready message ready_msg = await ws.recv() ready_data = json.loads(ready_msg) if ready_data.get("type") != "ready": print(f" WARNING: Expected 'ready', got: {ready_data}") else: print(f" Server ready")
ready_time = time.time()
# Track interim results interim_count = 0 last_interim = ""
# Create a task to receive messages async def receive_messages(): nonlocal interim_count, last_interim try: async for message in ws: data = json.loads(message) if data.get("type") == "transcript": text = data.get("text", "") is_final = data.get("is_final", False)
if is_final: return text else: interim_count += 1 last_interim = text # Show interim result (truncated) display = text[:60] + "..." if len(text) > 60 else text print(f" [interim {interim_count}] {display}") elif data.get("type") == "error": print(f" ERROR: {data.get('message')}") return None except websockets.exceptions.ConnectionClosed: return last_interim
# Start receiving in background receive_task = asyncio.create_task(receive_messages())
# Send audio data in chunks total_sent = 0 chunks_sent = 0
print(f"\nSending audio in {chunk_ms}ms chunks...") send_start = time.time()
for i in range(0, len(audio_data), chunk_bytes): chunk = audio_data[i:i+chunk_bytes] await ws.send(chunk) total_sent += len(chunk) chunks_sent += 1
# Simulate real-time streaming await asyncio.sleep(chunk_ms / 1000)
send_time = time.time() print(f" Sent {chunks_sent} chunks ({total_sent} bytes) in {(send_time - send_start)*1000:.0f}ms")
# Record time of last audio chunk sent last_audio_time = send_time
# Signal end of audio end_signal_time = time.time() await ws.send(json.dumps({"type": "reset"}))
# Wait for final transcript print("\nWaiting for final transcript...") transcript = await receive_task final_recv_time = time.time()
# Calculate time-to-final-transcription time_to_final = (final_recv_time - last_audio_time) * 1000 end_signal_to_final = (final_recv_time - end_signal_time) * 1000
print(f"\n{'='*60}") print("FINAL TRANSCRIPT:") print(f"{'='*60}") print(transcript if transcript else "(empty)") print(f"{'='*60}")
total_time = final_recv_time - start_time print(f"\nStatistics:") print(f" Interim results: {interim_count}") print(f" Total time: {total_time*1000:.0f}ms") print(f" Audio duration: {duration:.2f}s") print(f" Real-time factor: {total_time/duration:.2f}x") print(f"\nFinalization latency:") print(f" Last audio chunk -> final transcript: {time_to_final:.0f}ms") print(f" End signal -> final transcript: {end_signal_to_final:.0f}ms")
return transcript
async def test_multiple_chunk_sizes(audio_path: str, server_url: str): """Test with different chunk sizes.""" print("=" * 60) print("Testing Multiple Chunk Sizes") print("=" * 60)
for chunk_ms in [500, 160, 80]: print(f"\n{'='*60}") print(f"CHUNK SIZE: {chunk_ms}ms") print(f"{'='*60}")
try: await test_asr_streaming(audio_path, server_url, chunk_ms) except Exception as e: print(f"ERROR with {chunk_ms}ms chunks: {e}")
# Small delay between tests await asyncio.sleep(1)
if __name__ == "__main__":
import sys # sys.argv.append( '--all' )
audio_path = "./harvard_16k.wav" server_url = "ws://127.0.0.1:8080"
# Check for --all flag to test all chunk sizes if "--all" in sys.argv: asyncio.run(test_multiple_chunk_sizes(audio_path, server_url)) else: chunk_ms = 500 if "--chunk" in sys.argv: idx = sys.argv.index("--chunk") if idx + 1 < len(sys.argv): chunk_ms = int(sys.argv[idx + 1])
asyncio.run(test_asr_streaming(audio_path, server_url, chunk_ms))server_aware_streaming.pyAdded+815
test_websocket_client.pyAdded+182