Module livekit.plugins.nvidia
Sub-modules
livekit.plugins.nvidia.experimental
Classes
class EndpointingConfig (mode: Literal['low_latency'] = 'low_latency',
start_history: int | None = None,
start_threshold: float | None = None,
stop_history: int | None = None,
stop_threshold: float | None = None,
stop_history_eou: int | None = None,
stop_threshold_eou: float | None = None)-
Expand source code
@dataclass(frozen=True) class EndpointingConfig: """Configure NVIDIA Speech endpoint detection for streaming recognition. Attributes: mode: Endpointing preset. ``"low_latency"`` applies the plugin's low-latency defaults before any field overrides. start_history: VAD start-history override in audio frames. start_threshold: Dimensionless VAD speech-start threshold override. stop_history: VAD stop-history override in audio frames. stop_threshold: Dimensionless VAD speech-stop threshold override. stop_history_eou: End-of-utterance stop-history override in audio frames. stop_threshold_eou: Dimensionless end-of-utterance stop-threshold override. ``None`` leaves a field at the value selected by ``mode``. Values of ``-1`` or ``-1.0`` ask NVIDIA Speech to use its model default for that field. """ mode: EndpointingMode = "low_latency" start_history: int | None = None start_threshold: float | None = None stop_history: int | None = None stop_threshold: float | None = None stop_history_eou: int | None = None stop_threshold_eou: float | None = NoneConfigure NVIDIA Speech endpoint detection for streaming recognition.
Attributes
mode- Endpointing preset.
"low_latency"applies the plugin's low-latency defaults before any field overrides. start_history- VAD start-history override in audio frames.
start_threshold- Dimensionless VAD speech-start threshold override.
stop_history- VAD stop-history override in audio frames.
stop_threshold- Dimensionless VAD speech-stop threshold override.
stop_history_eou- End-of-utterance stop-history override in audio frames.
stop_threshold_eou- Dimensionless end-of-utterance stop-threshold override.
Noneleaves a field at the value selected bymode. Values of-1or-1.0ask NVIDIA Speech to use its model default for that field.Instance variables
var mode : Literal['low_latency']var start_history : int | Nonevar start_threshold : float | Nonevar stop_history : int | Nonevar stop_history_eou : int | Nonevar stop_threshold : float | Nonevar stop_threshold_eou : float | None
class STT (*,
model: str = 'parakeet-1.1b-en-US-asr-streaming-silero-vad-sortformer',
function_id: str = '1598d209-5e27-4d3c-8079-4751568b1081',
punctuate: bool = True,
language_code: str = 'en-US',
sample_rate: int = 16000,
server: str = 'grpc.nvcf.nvidia.com:443',
use_ssl: bool = True,
api_key: str | livekit.agents.types.NotGiven = NOT_GIVEN,
enable_diarization: bool = False,
max_speaker_count: int = 0,
interim_results: bool = True,
profanity_filter: bool = False,
verbatim_transcripts: bool = False,
boosted_lm_words: list[str] | None = None,
boosted_lm_score: float = 4.0,
endpointing: livekit.plugins.nvidia.stt.EndpointingConfig | None = None,
options: dict[str, typing.Any] | None = None,
enable_word_time_offsets: bool = True,
inference_mode: Literal['auto', 'streaming', 'offline'] = 'auto')-
Expand source code
class STT(stt.STT): def __init__( self, *, model: str = "parakeet-1.1b-en-US-asr-streaming-silero-vad-sortformer", function_id: str = "1598d209-5e27-4d3c-8079-4751568b1081", punctuate: bool = True, language_code: str = "en-US", sample_rate: int = 16000, server: str = "grpc.nvcf.nvidia.com:443", use_ssl: bool = True, api_key: NotGivenOr[str] = NOT_GIVEN, enable_diarization: bool = False, max_speaker_count: int = 0, interim_results: bool = True, profanity_filter: bool = False, verbatim_transcripts: bool = False, boosted_lm_words: list[str] | None = None, boosted_lm_score: float = 4.0, endpointing: EndpointingConfig | None = None, options: dict[str, Any] | None = None, enable_word_time_offsets: bool = True, inference_mode: InferenceMode = "auto", ): """Create an NVIDIA Speech recognition client. Args: model: NVIDIA Speech model name sent with recognition requests. function_id: NVIDIA-hosted NVCF function ID. Local deployments may use the value expected by their gateway. punctuate: Whether to enable automatic punctuation. language_code: Recognition language code, such as ``"en-US"``. sample_rate: Streaming input sample rate in Hz. server: NVIDIA Speech gRPC endpoint. use_ssl: Whether to use TLS for the gRPC connection. api_key: NVIDIA API key. When omitted, reads ``NVIDIA_API_KEY``. enable_diarization: Whether to request speaker diarization. max_speaker_count: Maximum expected speakers when diarization is enabled. interim_results: Whether streaming recognition emits interim transcripts. profanity_filter: Whether to mask profane words in transcripts. verbatim_transcripts: Whether to request verbatim transcript formatting. boosted_lm_words: Words or phrases to boost during recognition. boosted_lm_score: Global boost score applied to ``boosted_lm_words``. endpointing: Streaming endpoint-detection settings. ``None`` leaves the deployed model's endpointing configuration unchanged. options: Provider-specific escape hatch. ``recognition_config`` values are passed to ``riva.client.RecognitionConfig``; ``custom_configuration`` is applied to the streaming configuration when supported by the client. enable_word_time_offsets: Whether to request word timestamps. inference_mode: ``"streaming"`` or ``"offline"`` advertises only that capability; ``"auto"`` preserves support for both APIs. Raises: ValueError: If the inference mode is invalid or hosted authentication is enabled without an API key. """ if inference_mode not in ("auto", "streaming", "offline"): raise ValueError("inference_mode must be 'auto', 'streaming', or 'offline'") if enable_diarization and "sortformer" not in model.lower(): logger.warning( "Speaker diarization is enabled but model '%s' may not support it. " "Diarization requires a Sortformer-based model.", model, ) supports_streaming = inference_mode in ("auto", "streaming") supports_offline = inference_mode in ("auto", "offline") super().__init__( capabilities=stt.STTCapabilities( streaming=supports_streaming, interim_results=interim_results if supports_streaming else False, diarization=enable_diarization, aligned_transcript="word" if enable_word_time_offsets else False, offline_recognize=supports_offline, ), ) if is_given(api_key): self.nvidia_api_key = api_key else: self.nvidia_api_key = os.getenv("NVIDIA_API_KEY", "") if use_ssl and not self.nvidia_api_key: raise ValueError( "NVIDIA_API_KEY is not set while using SSL. Either pass api_key parameter, " "set NVIDIA_API_KEY environment variable or disable SSL and use a locally " "hosted NVIDIA Speech service." ) self._opts = STTOptions( model=model, function_id=function_id, punctuate=punctuate, language_code=LanguageCode(language_code), sample_rate=sample_rate, server=server, use_ssl=use_ssl, enable_diarization=enable_diarization, max_speaker_count=max_speaker_count, interim_results=interim_results, profanity_filter=profanity_filter, verbatim_transcripts=verbatim_transcripts, boosted_lm_words=boosted_lm_words, boosted_lm_score=boosted_lm_score, endpointing=endpointing, options=dict(options or {}), enable_word_time_offsets=enable_word_time_offsets, inference_mode=inference_mode, ) self._asr_service: riva.client.ASRService | None = None @property def model(self) -> str: return self._opts.model @property def provider(self) -> str: return "NVIDIA Speech" def _ensure_asr_service(self) -> riva.client.ASRService: if self._asr_service is None: riva_auth = auth.create_riva_auth( api_key=self.nvidia_api_key, function_id=self._opts.function_id, server=self._opts.server, use_ssl=self._opts.use_ssl, ) self._asr_service = riva.client.ASRService(riva_auth) return self._asr_service async def _recognize_impl( self, buffer: AudioBuffer, *, language: NotGivenOr[str] = NOT_GIVEN, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS, ) -> stt.SpeechEvent: if self._opts.inference_mode == "streaming": raise ValueError( "recognize() requires inference_mode='offline'; use stream() for streaming models" ) effective_language = ( LanguageCode(language) if is_given(language) else self._opts.language_code ) frame = rtc.combine_audio_frames(buffer) config = self._create_recognition_config( language=effective_language, sample_rate=frame.sample_rate, audio_channel_count=frame.num_channels, ) service = self._ensure_asr_service() try: response = await asyncio.wait_for( asyncio.to_thread(service.offline_recognize, frame.data.tobytes(), config), timeout=conn_options.timeout, ) except asyncio.TimeoutError: raise APITimeoutError("NVIDIA Speech STT request timed out") from None except Exception as e: raise to_api_error(e, operation="NVIDIA Speech offline STT request") from e return _response_to_speech_event( response, language=effective_language, request_id=f"nvidia-{id(response)}", event_type=stt.SpeechEventType.FINAL_TRANSCRIPT, enable_diarization=self._opts.enable_diarization, is_final=True, ) def stream( self, *, language: NotGivenOr[str] = NOT_GIVEN, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS, ) -> stt.RecognizeStream: if self._opts.inference_mode == "offline": raise ValueError( "stream() requires inference_mode='streaming'; use recognize() for offline models" ) effective_language = ( LanguageCode(language) if is_given(language) else self._opts.language_code ) return SpeechStream(stt=self, conn_options=conn_options, language=effective_language) def _create_recognition_config( self, *, language: LanguageCode, sample_rate: int, audio_channel_count: int, ) -> riva.client.RecognitionConfig: recognition_kwargs = { "encoding": riva.client.AudioEncoding.LINEAR_PCM, "language_code": language, "model": self._opts.model, "max_alternatives": 1, "profanity_filter": self._opts.profanity_filter, "enable_automatic_punctuation": self._opts.punctuate, "verbatim_transcripts": self._opts.verbatim_transcripts, "sample_rate_hertz": sample_rate, "audio_channel_count": audio_channel_count, "enable_word_time_offsets": self._opts.enable_word_time_offsets, } recognition_kwargs.update(self._opts.options.get("recognition_config", {})) recognition_config = riva.client.RecognitionConfig(**recognition_kwargs) if self._opts.enable_diarization: diarization_config = SpeakerDiarizationConfig( enable_speaker_diarization=True, max_speaker_count=self._opts.max_speaker_count, ) recognition_config.diarization_config.CopyFrom(diarization_config) if self._opts.boosted_lm_words: riva.client.add_word_boosting_to_config( recognition_config, self._opts.boosted_lm_words, self._opts.boosted_lm_score, ) return recognition_config def _apply_streaming_config_extensions( self, streaming_config: riva.client.StreamingRecognitionConfig, ) -> None: endpointing_values = _endpointing_values(self._opts.endpointing) if endpointing_values is not None: riva.client.add_endpoint_parameters_to_config( streaming_config, *endpointing_values, ) custom_configuration = self._opts.options.get("custom_configuration", "") if custom_configuration and hasattr(riva.client, "add_custom_configuration_to_config"): riva.client.add_custom_configuration_to_config( streaming_config, custom_configuration, ) elif custom_configuration: raise ValueError( "custom_configuration is not supported by the installed nvidia-riva-client " "version. Remove options['custom_configuration'] or install a version " "that exposes add_custom_configuration_to_config." ) def log_asr_models(self, asr_service: riva.client.ASRService) -> dict: config_response = asr_service.stub.GetRivaSpeechRecognitionConfig( RivaSpeechRecognitionConfigRequest() ) asr_models = {} for model_config in config_response.model_config: model_type = model_config.parameters.get("type") if self._opts.inference_mode == "auto" or model_type == ( "online" if self._opts.inference_mode == "streaming" else "offline" ): language_code = model_config.parameters["language_code"] model = {"model": [model_config.model_name]} if language_code in asr_models: asr_models[language_code].append(model) else: asr_models[language_code] = [model] asr_models = dict(sorted(asr_models.items())) return asr_modelsHelper class that provides a standard way to create an ABC using inheritance.
Create an NVIDIA Speech recognition client.
Args
model- NVIDIA Speech model name sent with recognition requests.
function_id- NVIDIA-hosted NVCF function ID. Local deployments may use the value expected by their gateway.
punctuate- Whether to enable automatic punctuation.
language_code- Recognition language code, such as
"en-US". sample_rate- Streaming input sample rate in Hz.
server- NVIDIA Speech gRPC endpoint.
use_ssl- Whether to use TLS for the gRPC connection.
api_key- NVIDIA API key. When omitted, reads
NVIDIA_API_KEY. enable_diarization- Whether to request speaker diarization.
max_speaker_count- Maximum expected speakers when diarization is enabled.
interim_results- Whether streaming recognition emits interim transcripts.
profanity_filter- Whether to mask profane words in transcripts.
verbatim_transcripts- Whether to request verbatim transcript formatting.
boosted_lm_words- Words or phrases to boost during recognition.
boosted_lm_score- Global boost score applied to
boosted_lm_words. endpointing- Streaming endpoint-detection settings.
Noneleaves the deployed model's endpointing configuration unchanged. options- Provider-specific escape hatch.
recognition_configvalues are passed toriva.client.RecognitionConfig;custom_configurationis applied to the streaming configuration when supported by the client. enable_word_time_offsets- Whether to request word timestamps.
inference_mode"streaming"or"offline"advertises only that capability;"auto"preserves support for both APIs.
Raises
ValueError- If the inference mode is invalid or hosted authentication is enabled without an API key.
Ancestors
- livekit.agents.stt.stt.STT
- abc.ABC
- EventEmitter
- typing.Generic
Instance variables
prop model : str-
Expand source code
@property def model(self) -> str: return self._opts.modelGet the model name/identifier for this STT instance.
Returns
The model name if available, "unknown" otherwise.
Note
Plugins should override this property to provide their model information.
prop provider : str-
Expand source code
@property def provider(self) -> str: return "NVIDIA Speech"Get the provider name/identifier for this STT instance.
Returns
The provider name if available, "unknown" otherwise.
Note
Plugins should override this property to provide their provider information.
Methods
def log_asr_models(self, asr_service: riva.client.asr.ASRService) ‑> dict-
Expand source code
def log_asr_models(self, asr_service: riva.client.ASRService) -> dict: config_response = asr_service.stub.GetRivaSpeechRecognitionConfig( RivaSpeechRecognitionConfigRequest() ) asr_models = {} for model_config in config_response.model_config: model_type = model_config.parameters.get("type") if self._opts.inference_mode == "auto" or model_type == ( "online" if self._opts.inference_mode == "streaming" else "offline" ): language_code = model_config.parameters["language_code"] model = {"model": [model_config.model_name]} if language_code in asr_models: asr_models[language_code].append(model) else: asr_models[language_code] = [model] asr_models = dict(sorted(asr_models.items())) return asr_models def stream(self,
*,
language: str | livekit.agents.types.NotGiven = NOT_GIVEN,
conn_options: livekit.agents.types.APIConnectOptions = APIConnectOptions(max_retry=3, retry_interval=2.0, timeout=10.0, liveness_timeout=6.0)) ‑> livekit.agents.stt.stt.RecognizeStream-
Expand source code
def stream( self, *, language: NotGivenOr[str] = NOT_GIVEN, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS, ) -> stt.RecognizeStream: if self._opts.inference_mode == "offline": raise ValueError( "stream() requires inference_mode='streaming'; use recognize() for offline models" ) effective_language = ( LanguageCode(language) if is_given(language) else self._opts.language_code ) return SpeechStream(stt=self, conn_options=conn_options, language=effective_language)
Inherited members
class SpeechStream (*,
stt: livekit.plugins.nvidia.stt.STT,
conn_options: livekit.agents.types.APIConnectOptions,
language: str)-
Expand source code
class SpeechStream(stt.SpeechStream): def __init__(self, *, stt: STT, conn_options: APIConnectOptions, language: str): super().__init__(stt=stt, conn_options=conn_options, sample_rate=stt._opts.sample_rate) self._stt = stt self._language = language self._speaking = False self._request_id = "" self._max_replay_bytes = ( stt._opts.sample_rate * _PCM_BYTES_PER_SAMPLE * _MAX_REPLAY_AUDIO_SECONDS ) self._asr_service = self._stt._ensure_asr_service() async def _run(self) -> None: config = self._create_streaming_config() event_loop = asyncio.get_running_loop() active_attempt: _RecognitionAttempt | None = None streaming_retry_count = 0 input_aiter = self._input_ch.__aiter__() input_task = asyncio.create_task(anext(input_aiter)) try: while True: waiters: set[asyncio.Future[Any]] = {input_task} if active_attempt is not None: waiters.add(active_attempt.done_fut) completed, _ = await asyncio.wait( waiters, return_when=asyncio.FIRST_COMPLETED, ) if input_task in completed: try: data = input_task.result() except StopAsyncIteration: break if isinstance(data, rtc.AudioFrame): audio_bytes = data.data.tobytes() if audio_bytes: if active_attempt is None: active_attempt = self._start_recognition_attempt(config, event_loop) active_attempt.buffer_for_replay( audio_bytes, max_bytes=self._max_replay_bytes, ) active_attempt.audio_queue.put(audio_bytes) elif isinstance(data, self._FlushSentinel) and active_attempt is not None: await self._finish_recognition_segment( config=config, attempt=active_attempt, event_loop=event_loop, ) active_attempt = None streaming_retry_count = 0 self._input_ch.restart_provider_clock() input_task = asyncio.create_task(anext(input_aiter)) if active_attempt is not None and active_attempt.done_fut.done(): active_attempt, streaming_retry_count = await self._restart_streaming_attempt( config=config, attempt=active_attempt, event_loop=event_loop, retry_count=streaming_retry_count, ) finally: input_task.cancel() with suppress(asyncio.CancelledError, StopAsyncIteration): await input_task if active_attempt is not None: _close_attempt_input(active_attempt) with suppress(asyncio.CancelledError, asyncio.TimeoutError, Exception): await asyncio.wait_for(asyncio.shield(active_attempt.done_fut), timeout=1.0) await _join_attempt(active_attempt) def _start_recognition_attempt( self, config: riva.client.StreamingRecognitionConfig, event_loop: asyncio.AbstractEventLoop, *, start_time_offset: float | None = None, ) -> _RecognitionAttempt: audio_queue: queue.Queue[bytes | None] = queue.Queue() done_fut: asyncio.Future[None] = event_loop.create_future() attempt = _RecognitionAttempt( audio_queue=audio_queue, done_fut=done_fut, start_time_offset=( self.start_time_offset if start_time_offset is None else start_time_offset ), bytes_per_second=self._stt._opts.sample_rate * _PCM_BYTES_PER_SAMPLE, ) recognition_thread = threading.Thread( target=self._recognition_worker, args=(config, attempt, event_loop), name="nvidia-asr-recognition", daemon=True, ) attempt.thread = recognition_thread recognition_thread.start() return attempt async def _restart_streaming_attempt( self, *, config: riva.client.StreamingRecognitionConfig, attempt: _RecognitionAttempt, event_loop: asyncio.AbstractEventLoop, retry_count: int, ) -> tuple[_RecognitionAttempt, int]: api_error: APIError | None = None try: attempt.done_fut.result() except APIError as error: api_error = error _close_attempt_input(attempt) await _join_attempt(attempt) made_progress = attempt.received_final_transcript() if made_progress: retry_count = 0 if api_error is not None and not api_error.retryable: raise api_error replay_audio, replay_offset, _ = attempt.replay_snapshot() clean_completion_after_progress = api_error is None and made_progress if not clean_completion_after_progress and retry_count == self._conn_options.max_retry: reason = "ended unexpectedly" if api_error is None else "failed" raise APIConnectionError( f"NVIDIA Speech streaming STT {reason} after {retry_count + 1} attempts", retryable=False, ) from api_error if not clean_completion_after_progress: await asyncio.sleep(self._conn_options._interval_for_retry(retry_count)) next_attempt = self._start_recognition_attempt( config, event_loop, start_time_offset=replay_offset ) for audio_chunk in replay_audio: next_attempt.buffer_for_replay(audio_chunk, max_bytes=self._max_replay_bytes) next_attempt.audio_queue.put(audio_chunk) return next_attempt, 0 if clean_completion_after_progress else retry_count + 1 async def _finish_recognition_segment( self, *, config: riva.client.StreamingRecognitionConfig, attempt: _RecognitionAttempt, event_loop: asyncio.AbstractEventLoop, ) -> None: current_attempt = attempt retry_count = 0 try: while True: attempt_to_join = current_attempt _close_attempt_input(current_attempt) try: await current_attempt.done_fut break except APIError: replay_audio, _, final_transcript_emitted = current_attempt.replay_snapshot() if final_transcript_emitted and not replay_audio: logger.warning( "NVIDIA Speech stream failed after a final transcript; " "not replaying audio" ) break current_attempt, retry_count = await self._restart_streaming_attempt( config=config, attempt=current_attempt, event_loop=event_loop, retry_count=retry_count, ) finally: await _join_attempt(attempt_to_join) finally: self._finish_speech_segment() def _finish_speech_segment(self) -> None: if self._speaking: self._speaking = False self._event_ch.send_nowait(stt.SpeechEvent(type=stt.SpeechEventType.END_OF_SPEECH)) self._request_id = "" def _create_streaming_config(self) -> riva.client.StreamingRecognitionConfig: recognition_config = self._stt._create_recognition_config( language=LanguageCode(self._language), sample_rate=self._stt._opts.sample_rate, audio_channel_count=1, ) streaming_config = riva.client.StreamingRecognitionConfig( config=recognition_config, interim_results=self._stt._opts.interim_results, ) self._stt._apply_streaming_config_extensions(streaming_config) return streaming_config def _recognition_worker( self, config: riva.client.StreamingRecognitionConfig, attempt: _RecognitionAttempt, event_loop: asyncio.AbstractEventLoop, ) -> None: error: Exception | None = None try: audio_generator = self._audio_chunk_generator(attempt.audio_queue) response_generator = self._asr_service.streaming_response_generator( audio_generator, config ) for response in response_generator: if self._handle_response( response, event_loop=event_loop, start_time_offset=attempt.start_time_offset ): attempt.mark_final_transcript() except Exception as e: error = e finally: event_loop.call_soon_threadsafe(self._complete_done_future, attempt.done_fut, error) def _complete_done_future( self, done_fut: asyncio.Future[None], error: Exception | None ) -> None: if done_fut.done(): return if error is not None: done_fut.set_exception( to_api_error(error, operation="NVIDIA Speech streaming STT request") ) else: done_fut.set_result(None) def _audio_chunk_generator( self, audio_queue: queue.Queue[bytes | None] ) -> Generator[bytes, None, None]: """ The NVIDIA Speech SDK requires a generator for realtime STT, so the LiveKit async input channel is bridged through a thread-safe queue. """ while True: audio_chunk = audio_queue.get() if not audio_chunk: break yield audio_chunk def _handle_response( self, response: Any, *, event_loop: asyncio.AbstractEventLoop, start_time_offset: float, ) -> bool: final_transcript_emitted = False if not hasattr(response, "results") or not response.results: return False self._request_id = f"nvidia-{id(response)}" for result in response.results: if not hasattr(result, "alternatives") or not result.alternatives: continue event_loop.call_soon_threadsafe(self._mark_provider_progress) alternative = result.alternatives[0] transcript = getattr(alternative, "transcript", "") is_final = getattr(result, "is_final", False) if not transcript.strip(): continue if not self._speaking: self._speaking = True event_loop.call_soon_threadsafe( self._event_ch.send_nowait, stt.SpeechEvent(type=stt.SpeechEventType.START_OF_SPEECH), ) speech_data = _convert_to_speech_data( alternative, language=LanguageCode(self._language), start_time_offset=start_time_offset, enable_diarization=self._stt._opts.enable_diarization, is_final=is_final, ) event_type = ( stt.SpeechEventType.FINAL_TRANSCRIPT if is_final else stt.SpeechEventType.INTERIM_TRANSCRIPT ) event_loop.call_soon_threadsafe( self._event_ch.send_nowait, stt.SpeechEvent( type=event_type, request_id=self._request_id, alternatives=[speech_data], ), ) if is_final and self._speaking: final_transcript_emitted = True self._speaking = False event_loop.call_soon_threadsafe( self._event_ch.send_nowait, stt.SpeechEvent(type=stt.SpeechEventType.END_OF_SPEECH), ) return final_transcript_emittedHelper class that provides a standard way to create an ABC using inheritance.
Args: sample_rate : int or None, optional The desired sample rate for the audio input. If specified, the audio input will be automatically resampled to match the given sample rate before being processed for Speech-to-Text. If not provided (None), the input will retain its original sample rate.
Ancestors
- livekit.agents.stt.stt.RecognizeStream
- abc.ABC
class SynthesizeStream (*,
tts: livekit.plugins.nvidia.tts.TTS,
conn_options: livekit.agents.types.APIConnectOptions,
opts: livekit.plugins.nvidia.tts.TTSOptions)-
Expand source code
class SynthesizeStream(tts.SynthesizeStream): def __init__(self, *, tts: TTS, conn_options: APIConnectOptions, opts: TTSOptions): super().__init__(tts=tts, conn_options=conn_options) self._tts: TTS = tts self._opts = replace(opts) async def _run(self, output_emitter: tts.AudioEmitter) -> None: context_id = utils.shortuuid() sent_tokenizer_stream = self._opts.word_tokenizer.stream() token_q: queue.Queue = queue.Queue() event_loop = asyncio.get_running_loop() output_emitter.initialize( request_id=context_id, sample_rate=self._opts.sample_rate, num_channels=1, stream=True, mime_type="audio/pcm", ) output_emitter.start_segment(segment_id=context_id) done_fut: asyncio.Future[None] = asyncio.Future() async def _input_task() -> None: async for data in self._input_ch: if isinstance(data, self._FlushSentinel): sent_tokenizer_stream.flush() break sent_tokenizer_stream.push_text(data) sent_tokenizer_stream.end_input() async def _process_segments() -> None: async for word_stream in sent_tokenizer_stream: token = word_stream.token if not token.strip(): continue self._mark_started() token_q.put(token) token_q.put(None) def _synthesize_worker() -> None: error: Exception | None = None try: while True: token = token_q.get() if not token: break for response in self._tts._synthesize(token, self._opts): event_loop.call_soon_threadsafe(output_emitter.push, response.audio) except Exception as e: error = e finally: event_loop.call_soon_threadsafe(_complete_future, done_fut, error) synthesize_thread = threading.Thread( target=_synthesize_worker, name="nvidia-tts-synthesize", daemon=True, ) synthesize_thread.start() tasks = [ asyncio.create_task(_input_task()), asyncio.create_task(_process_segments()), ] input_done = asyncio.gather(*tasks) try: await asyncio.wait([input_done, done_fut], return_when=asyncio.FIRST_COMPLETED) if done_fut.done(): done_fut.result() await input_done await done_fut finally: for task in tasks: task.cancel() input_done.cancel() await asyncio.gather(input_done, *tasks, return_exceptions=True) done_fut.cancel() token_q.put(None) output_emitter.end_segment() await sent_tokenizer_stream.aclose()Helper class that provides a standard way to create an ABC using inheritance.
Ancestors
- livekit.agents.tts.tts.SynthesizeStream
- abc.ABC
class TTS (*,
server: str = 'grpc.nvcf.nvidia.com:443',
voice: str = 'Magpie-Multilingual.EN-US.Leo',
function_id: str = '877104f7-e885-42b9-8de8-f6e4c6303969',
language_code: str = 'en-US',
sample_rate: int = 16000,
use_ssl: bool = True,
api_key: str | livekit.agents.types.NotGiven | None = NOT_GIVEN,
audio_prompt_file: str | os.PathLike[str] | None = None,
quality: int | None = None,
word_tokenizer: livekit.agents.tokenize.tokenizer.WordTokenizer | livekit.agents.tokenize.tokenizer.SentenceTokenizer | None = None,
options: dict[str, typing.Any] | None = None,
inference_mode: Literal['online', 'offline'] = 'online')-
Expand source code
class TTS(tts.TTS): def __init__( self, *, server: str = "grpc.nvcf.nvidia.com:443", voice: str = "Magpie-Multilingual.EN-US.Leo", function_id: str = "877104f7-e885-42b9-8de8-f6e4c6303969", language_code: str = "en-US", sample_rate: int = 16000, use_ssl: bool = True, api_key: NotGivenOr[str | None] = NOT_GIVEN, audio_prompt_file: str | PathLike[str] | None = None, quality: int | None = None, word_tokenizer: tokenize.WordTokenizer | tokenize.SentenceTokenizer | None = None, options: dict[str, Any] | None = None, inference_mode: InferenceMode = "online", ): """Create an NVIDIA Speech synthesis client. Args: server: NVIDIA Speech gRPC endpoint. voice: Voice name exposed by the deployed synthesis model. function_id: NVIDIA-hosted NVCF function ID. Local deployments may use the value expected by their gateway. language_code: Synthesis language code, such as ``"en-US"``. sample_rate: Output PCM sample rate in Hz. use_ssl: Whether to use TLS for the gRPC connection. api_key: NVIDIA API key. When omitted, ``None``, or empty, reads ``NVIDIA_API_KEY``. audio_prompt_file: Reference-audio path for models supporting zero-shot voice prompting. quality: Zero-shot synthesis quality accepted by compatible clients. word_tokenizer: Tokenizer used to split text submitted through ``stream()`` into synthesis requests. options: Additional keyword arguments passed to the installed NVIDIA synthesis client after compatibility validation. inference_mode: ``"online"`` uses streaming synthesis; ``"offline"`` uses the batch synthesis RPC. Raises: ValueError: If the inference mode is invalid or hosted authentication is enabled without an API key. """ if inference_mode not in ("online", "offline"): raise ValueError("inference_mode must be either 'online' or 'offline'") super().__init__( capabilities=tts.TTSCapabilities(streaming=True), sample_rate=sample_rate, num_channels=1, ) self.nvidia_api_key = ( api_key if is_given(api_key) and api_key else os.getenv("NVIDIA_API_KEY") ) if use_ssl and not self.nvidia_api_key: raise ValueError( "NVIDIA_API_KEY is not set while using SSL. Either pass api_key parameter, " "set NVIDIA_API_KEY environment variable or disable SSL and use a locally " "hosted NVIDIA Speech service." ) self._opts = TTSOptions( voice=voice, function_id=function_id, server=server, sample_rate=sample_rate, use_ssl=use_ssl, language_code=language_code, word_tokenizer=word_tokenizer or tokenize.blingfire.SentenceTokenizer(), audio_prompt_file=audio_prompt_file, quality=quality, options=dict(options or {}), inference_mode=inference_mode, ) self._tts_service: riva.client.SpeechSynthesisService | None = None @property def model(self) -> str: return self._opts.voice.split(".", 1)[0] @property def provider(self) -> str: return "NVIDIA Speech" def _ensure_session(self) -> riva.client.SpeechSynthesisService: if not self._tts_service: riva_auth = auth.create_riva_auth( api_key=self.nvidia_api_key, function_id=self._opts.function_id, server=self._opts.server, use_ssl=self._opts.use_ssl, ) self._tts_service = riva.client.SpeechSynthesisService(riva_auth) return self._tts_service def _synthesize(self, text: str, opts: TTSOptions): service = self._ensure_session() synthesize_method = ( service.synthesize_online if opts.inference_mode == "online" else service.synthesize ) parameters = inspect.signature(synthesize_method).parameters kwargs = dict(opts.options) kwargs.update( { "sample_rate_hz": opts.sample_rate, "encoding": AudioEncoding.LINEAR_PCM, } ) if opts.audio_prompt_file is not None: _set_compatible_option( kwargs, parameters=parameters, names=("zero_shot_audio_prompt_file", "audio_prompt_file"), value=Path(opts.audio_prompt_file), option_name="audio_prompt_file", ) if opts.quality is not None: _set_compatible_option( kwargs, parameters=parameters, names=("zero_shot_quality", "quality"), value=opts.quality, option_name="quality", ) if opts.inference_mode == "offline": kwargs["future"] = False if not any(param.kind == inspect.Parameter.VAR_KEYWORD for param in parameters.values()): unsupported = kwargs.keys() - parameters.keys() if unsupported: names = ", ".join(sorted(unsupported)) raise ValueError( f"The installed nvidia-riva-client does not support TTS option(s): {names}" ) response = synthesize_method( text.lstrip("\n").strip(), opts.voice, opts.language_code, **kwargs, ) if opts.inference_mode == "online": return response return iter((response,)) def list_voices(self) -> dict: service = self._ensure_session() config_response = service.stub.GetRivaSynthesisConfig( riva.client.proto.riva_tts_pb2.RivaSynthesisConfigRequest() ) tts_models = {} for model_config in config_response.model_config: language_codes = [ code.strip() for code in model_config.parameters.get("language_code", "").split(",") if code.strip() ] or ["unknown"] voice_name = model_config.parameters.get("voice_name", "unknown") subvoices_str = model_config.parameters.get("subvoices", "") if subvoices_str: subvoices = [voice.split(":")[0] for voice in subvoices_str.split(",")] full_voice_names = [voice_name + "." + subvoice for subvoice in subvoices] else: full_voice_names = [voice_name] for language_code in language_codes: voices = tts_models.setdefault(language_code, {"voices": []})["voices"] for full_voice_name in full_voice_names: if full_voice_name not in voices: voices.append(full_voice_name) tts_models = dict(sorted(tts_models.items())) return tts_models def synthesize( self, text: str, *, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS ) -> tts.ChunkedStream: return ChunkedStream(tts=self, input_text=text, conn_options=conn_options) def stream( self, *, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS ) -> tts.SynthesizeStream: return SynthesizeStream(tts=self, conn_options=conn_options, opts=self._opts)Helper class that provides a standard way to create an ABC using inheritance.
Create an NVIDIA Speech synthesis client.
Args
server- NVIDIA Speech gRPC endpoint.
voice- Voice name exposed by the deployed synthesis model.
function_id- NVIDIA-hosted NVCF function ID. Local deployments may use the value expected by their gateway.
language_code- Synthesis language code, such as
"en-US". sample_rate- Output PCM sample rate in Hz.
use_ssl- Whether to use TLS for the gRPC connection.
api_key- NVIDIA API key. When omitted,
None, or empty, readsNVIDIA_API_KEY. audio_prompt_file- Reference-audio path for models supporting zero-shot voice prompting.
quality- Zero-shot synthesis quality accepted by compatible clients.
word_tokenizer- Tokenizer used to split text submitted through
stream()into synthesis requests. options- Additional keyword arguments passed to the installed NVIDIA synthesis client after compatibility validation.
inference_mode"online"uses streaming synthesis;"offline"uses the batch synthesis RPC.
Raises
ValueError- If the inference mode is invalid or hosted authentication is enabled without an API key.
Ancestors
- livekit.agents.tts.tts.TTS
- abc.ABC
- EventEmitter
- typing.Generic
Instance variables
prop model : str-
Expand source code
@property def model(self) -> str: return self._opts.voice.split(".", 1)[0]Get the model name/identifier for this TTS instance.
Returns
The model name if available, "unknown" otherwise.
Note
Plugins should override this property to provide their model information.
prop provider : str-
Expand source code
@property def provider(self) -> str: return "NVIDIA Speech"Get the provider name/identifier for this TTS instance.
Returns
The provider name if available, "unknown" otherwise.
Note
Plugins should override this property to provide their provider information.
Methods
def list_voices(self) ‑> dict-
Expand source code
def list_voices(self) -> dict: service = self._ensure_session() config_response = service.stub.GetRivaSynthesisConfig( riva.client.proto.riva_tts_pb2.RivaSynthesisConfigRequest() ) tts_models = {} for model_config in config_response.model_config: language_codes = [ code.strip() for code in model_config.parameters.get("language_code", "").split(",") if code.strip() ] or ["unknown"] voice_name = model_config.parameters.get("voice_name", "unknown") subvoices_str = model_config.parameters.get("subvoices", "") if subvoices_str: subvoices = [voice.split(":")[0] for voice in subvoices_str.split(",")] full_voice_names = [voice_name + "." + subvoice for subvoice in subvoices] else: full_voice_names = [voice_name] for language_code in language_codes: voices = tts_models.setdefault(language_code, {"voices": []})["voices"] for full_voice_name in full_voice_names: if full_voice_name not in voices: voices.append(full_voice_name) tts_models = dict(sorted(tts_models.items())) return tts_models def stream(self,
*,
conn_options: livekit.agents.types.APIConnectOptions = APIConnectOptions(max_retry=3, retry_interval=2.0, timeout=10.0, liveness_timeout=6.0)) ‑> livekit.agents.tts.tts.SynthesizeStream-
Expand source code
def stream( self, *, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS ) -> tts.SynthesizeStream: return SynthesizeStream(tts=self, conn_options=conn_options, opts=self._opts) def synthesize(self,
text: str,
*,
conn_options: livekit.agents.types.APIConnectOptions = APIConnectOptions(max_retry=3, retry_interval=2.0, timeout=10.0, liveness_timeout=6.0)) ‑> livekit.agents.tts.tts.ChunkedStream-
Expand source code
def synthesize( self, text: str, *, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS ) -> tts.ChunkedStream: return ChunkedStream(tts=self, input_text=text, conn_options=conn_options)
Inherited members