Files

546 lines
19 KiB
Python

# Copyright 2023 LiveKit, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations
import asyncio
import base64
import os
from collections.abc import Iterable
from dataclasses import dataclass, replace
from typing import Literal, NotRequired, TypedDict, cast
import httpx
from livekit.agents import (
APIConnectionError,
APIConnectOptions,
APIError,
APIStatusError,
APITimeoutError,
tokenize,
tts,
utils,
)
from livekit.agents.types import (
NOT_GIVEN,
NotGivenOr,
)
from livekit.agents.utils import is_given
from livekit.agents.voice.io import TranscriptChunk
from speechify.client import AsyncSpeechify
from speechify.core.api_error import ApiError
from speechify.core.request_options import RequestOptions
from speechify.environment import SpeechifyEnvironment
from speechify.types.get_speech_options_request import GetSpeechOptionsRequest
from speechify.types.get_stream_options_request import GetStreamOptionsRequest
from speechify.types.get_voice import GetVoice
from speechify.types.nested_chunk import NestedChunk
from speechify.types.speech_stream_event import (
SpeechStreamEvent_SpeechChunk,
SpeechStreamEvent_SpeechDone,
SpeechStreamEvent_SpeechError,
)
from .log import logger
from .models import Gender, TTSModels, VoiceType
from .version import __version__
DEFAULT_VOICE_ID = "dominic_32"
DEFAULT_MODEL: TTSModels = "simba-3.2"
SAMPLE_RATE = 24000
NUM_CHANNELS = 1
AUDIO_FORMAT: Literal["pcm"] = "pcm"
MIME_TYPE = "audio/pcm"
CALLER_HEADER = "Speechify-Caller"
CALLER_VERSION_HEADER = "Speechify-Caller-Version"
# Unauthenticated, so warming the connection never presents the API key.
PREWARM_PATH = "/health"
@dataclass
class _TTSOptions:
voice_id: str
model: NotGivenOr[TTSModels]
language: NotGivenOr[str]
loudness_normalization: NotGivenOr[bool]
text_normalization: NotGivenOr[bool]
@dataclass
class Voice:
id: str
type: VoiceType
display_name: str
gender: Gender
avatar_image: str | None
models: list[TTSModels]
locale: str
def _voice_from_sdk(v: GetVoice) -> Voice:
# The SDK exposes "notSpecified"; the plugin's Gender literal is "neutral".
gender = "neutral" if v.gender == "notSpecified" else v.gender
return Voice(
id=v.id,
type=cast(VoiceType, v.type),
display_name=v.display_name,
gender=cast(Gender, gender),
avatar_image=v.avatar_image,
models=[cast(TTSModels, m.name) for m in v.models],
locale=v.locale,
)
class TTS(tts.TTS):
def __init__(
self,
*,
voice_id: str = DEFAULT_VOICE_ID,
model: TTSModels = DEFAULT_MODEL,
language: NotGivenOr[str] = NOT_GIVEN,
loudness_normalization: NotGivenOr[bool] = NOT_GIVEN,
text_normalization: NotGivenOr[bool] = NOT_GIVEN,
api_key: NotGivenOr[str] = NOT_GIVEN,
base_url: NotGivenOr[str] = NOT_GIVEN,
client: AsyncSpeechify | None = None,
) -> None:
"""Create a new instance of Speechify TTS.
Both ``synthesize()`` and ``stream()`` use the
``/v1/audio/stream/with-timestamps`` endpoint, which streams raw PCM
(24 kHz mono) together with word-level speech marks, so audio and aligned
timestamps are emitted as they arrive. ``stream()`` issues one streaming
request per text chunk the framework prepares. Speech marks are
produced by the streaming-native models (``simba-3.0`` and ``simba-3.2``);
the legacy ``simba-english`` and ``simba-multilingual`` models do not
serve the streaming route and use one non-streamed ``/v1/audio/speech``
request per input (``synthesize()``) or per chunk (``stream()``).
Requests share one keep-alive connection, which ``prewarm()`` opens
before the first request.
Args:
voice_id: Id of the voice to synthesize with. The voice must support
the chosen ``model`` (see the ``/v1/voices`` endpoint). Defaults
to ``dominic_32``. Voices whose id carries a ``_32`` suffix are
part of the curated simba-3.2 roster; a warning is logged when
they are paired with any other model.
model: Synthesis model. One of ``simba-english``,
``simba-multilingual``, ``simba-3.0`` or ``simba-3.2``. Defaults
to ``simba-3.2``.
language: BCP-47 language code of the input (e.g. ``en-US``).
loudness_normalization: Normalize output loudness to a standard
level. Increases latency slightly when enabled.
text_normalization: Expand numbers, dates, etc. into words before
synthesis. Increases latency slightly when enabled.
api_key: Speechify API key. Falls back to the ``SPEECHIFY_API_KEY``
environment variable.
base_url: Override the Speechify API base URL.
client: A preconfigured ``AsyncSpeechify`` client. When provided,
``api_key`` and ``base_url`` are ignored.
"""
super().__init__(
capabilities=tts.TTSCapabilities(streaming=True, aligned_transcript=True),
sample_rate=SAMPLE_RATE,
num_channels=NUM_CHANNELS,
)
self._owns_client = client is None
self._prewarm_task: asyncio.Task[None] | None = None
self._tasks = utils.aio.TaskSet()
self._base_url = base_url if is_given(base_url) else SpeechifyEnvironment.DEFAULT.value
if client is not None:
self._client = client
else:
resolved_key = api_key if is_given(api_key) else os.environ.get("SPEECHIFY_API_KEY")
if not resolved_key:
raise ValueError(
"Speechify API key is required, either as the api_key argument "
"or via the SPEECHIFY_API_KEY environment variable"
)
# Reuse the SDK's HTTP client type so its transport errors retain their taxonomy.
self._httpx_client = httpx.AsyncClient(
headers={CALLER_HEADER: "livekit", CALLER_VERSION_HEADER: __version__},
timeout=httpx.Timeout(connect=15.0, read=30.0, write=30.0, pool=5.0),
limits=httpx.Limits(
max_connections=50, max_keepalive_connections=50, keepalive_expiry=120
),
)
self._client = AsyncSpeechify(
token=resolved_key,
base_url=self._base_url,
httpx_client=self._httpx_client,
)
self._opts = _TTSOptions(
voice_id=voice_id,
model=model,
language=language,
loudness_normalization=loudness_normalization,
text_normalization=text_normalization,
)
_warn_voice_model_compat(self._opts.voice_id, self._opts.model)
@property
def model(self) -> str:
return self._opts.model if is_given(self._opts.model) else "unknown"
@property
def provider(self) -> str:
return "speechify"
def prewarm(self) -> None:
"""Open the HTTPS connection to the Speechify API ahead of the first request.
Sends an unauthenticated ``GET /health`` through the connection pool the
synthesis requests use, so the first reply of a session does not pay for
DNS, TCP and TLS setup. Does nothing when a preconfigured ``client`` was
passed in, because the plugin does not own that client's connections.
"""
if not self._owns_client or self._tasks.closed:
return
async def _prewarm() -> None:
try:
await self._httpx_client.get(self._base_url.rstrip("/") + PREWARM_PATH)
except Exception:
pass
if self._prewarm_task is None or self._prewarm_task.done():
self._prewarm_task = self._tasks.spawn(_prewarm())
async def aclose(self) -> None:
await self._tasks.aclose()
if self._owns_client:
await self._httpx_client.aclose()
async def list_voices(self) -> list[Voice]:
"""List the voices available for the configured Speechify account."""
sdk_voices = await self._client.voices.list()
return [_voice_from_sdk(v) async for v in sdk_voices]
def update_options(
self,
*,
voice_id: NotGivenOr[str] = NOT_GIVEN,
model: NotGivenOr[TTSModels] = NOT_GIVEN,
language: NotGivenOr[str] = NOT_GIVEN,
loudness_normalization: NotGivenOr[bool] = NOT_GIVEN,
text_normalization: NotGivenOr[bool] = NOT_GIVEN,
sentence_tokenizer: NotGivenOr[tokenize.SentenceTokenizer] = NOT_GIVEN,
pacing: NotGivenOr[tts.SentenceStreamPacer | None] = NOT_GIVEN,
) -> None:
with self._updating_options(sentence_tokenizer=sentence_tokenizer, pacing=pacing):
if is_given(voice_id):
self._opts.voice_id = voice_id
if is_given(model):
self._opts.model = model
if is_given(language):
self._opts.language = language
if is_given(loudness_normalization):
self._opts.loudness_normalization = loudness_normalization
if is_given(text_normalization):
self._opts.text_normalization = text_normalization
_warn_voice_model_compat(self._opts.voice_id, self._opts.model)
def _synthesize(
self, chunk: tts.SpeechChunk, *, conn_options: APIConnectOptions
) -> ChunkedStream:
return ChunkedStream(
tts=self,
input_text=chunk.text,
conn_options=conn_options,
opts=replace(self._opts),
client=self._client,
)
def _stream(self, *, conn_options: APIConnectOptions) -> SynthesizeStream:
return SynthesizeStream(
tts=self,
conn_options=conn_options,
opts=replace(self._opts),
client=self._client,
)
class _Request(TypedDict):
input: str
voice_id: str
model: NotRequired[TTSModels]
language: NotRequired[str]
class _SpeechRequest(_Request):
audio_format: Literal["pcm"]
options: NotRequired[GetSpeechOptionsRequest]
class _StreamRequest(_Request):
output_format: Literal["pcm_24000"]
options: NotRequired[GetStreamOptionsRequest]
def _normalization_options(opts: _TTSOptions) -> dict[str, bool]:
options: dict[str, bool] = {}
if is_given(opts.loudness_normalization):
options["loudness_normalization"] = opts.loudness_normalization
if is_given(opts.text_normalization):
options["text_normalization"] = opts.text_normalization
return options
def _request_kwargs(text: str, opts: _TTSOptions) -> _SpeechRequest:
options = _normalization_options(opts)
kwargs: _SpeechRequest = {
"audio_format": AUDIO_FORMAT,
"input": text,
"voice_id": opts.voice_id,
}
if is_given(opts.model):
kwargs["model"] = opts.model
if is_given(opts.language):
kwargs["language"] = opts.language
if options:
kwargs["options"] = GetSpeechOptionsRequest(**options)
return kwargs
def _stream_request_kwargs(text: str, opts: _TTSOptions) -> _StreamRequest:
options = _normalization_options(opts)
kwargs: _StreamRequest = {
"input": text,
"voice_id": opts.voice_id,
"output_format": "pcm_24000",
}
if is_given(opts.model):
kwargs["model"] = opts.model
if is_given(opts.language):
kwargs["language"] = opts.language
if options:
kwargs["options"] = GetStreamOptionsRequest(**options)
return kwargs
def _supports_streaming_marks(model: NotGivenOr[TTSModels]) -> bool:
# The streaming route serves word-level marks only on the streaming-native
# models; when no model is given the server defaults to simba-3.0.
if not is_given(model):
return True
return model in ("simba-3.0", "simba-3.2")
def _warn_voice_model_compat(voice_id: str, model: NotGivenOr[TTSModels]) -> None:
# simba-3.2 serves a curated stock roster whose ids carry a "_32" suffix
# (e.g. "dominic_32"). Such voices are tuned for simba-3.2; pairing them
# with another model is likely to be rejected or sub-optimal.
if is_given(model) and model == "simba-3.2":
return
if not voice_id.endswith("_32"):
return
effective = model if is_given(model) else "simba-3.0 (server default)"
logger.warning(
f"voice {voice_id!r} is part of the curated simba-3.2 roster but the "
f"configured model is {effective!r}; this pairing may be unsupported. "
"Set model='simba-3.2' when using a '*_32' voice."
)
def _marks_to_timed(chunks: Iterable[NestedChunk], offset: float) -> list[TranscriptChunk]:
out: list[TranscriptChunk] = []
for chunk in chunks:
value = chunk.value
start = chunk.start_time
if value is None or start is None:
continue
end = chunk.end_time
out.append(
TranscriptChunk(
text=value,
start_time=start / 1000 + offset,
end_time=(end / 1000 + offset) if end is not None else None,
)
)
return out
async def _synthesize_text(
client: AsyncSpeechify,
text: str,
opts: _TTSOptions,
conn_options: APIConnectOptions,
output_emitter: tts.AudioEmitter,
*,
offset: float,
) -> int:
"""Synthesize ``text`` into ``output_emitter`` and return the PCM bytes pushed.
``offset`` (seconds) shifts the word timestamps onto the emitter's timeline.
"""
timeout = conn_options.connect_timeout
if (
timeout is None
or conn_options.pool_timeout != timeout
or conn_options.read_timeout != timeout
or conn_options.write_timeout != timeout
or not float(timeout).is_integer()
):
raise APIError(
"Speechify SDK applies one finite limit, in whole seconds, to every phase: "
"pool/connect/write/read timeouts must be equal",
kind="invalid_request",
)
request_options: RequestOptions = {"timeout_in_seconds": int(timeout), "max_retries": 0}
if not _supports_streaming_marks(opts.model):
response = await client.audio.speech(
**_request_kwargs(text, opts), request_options=request_options
)
audio = base64.b64decode(response.audio_data)
timed = _marks_to_timed(response.speech_marks.chunks, offset)
if timed:
output_emitter.push_timed_transcript(timed)
output_emitter.push(audio)
output_emitter.report_usage(characters_count=response.billable_characters_count)
return len(audio)
pushed = 0
stream = client.audio.stream_with_timestamps(
**_stream_request_kwargs(text, opts), request_options=request_options
)
# Drain past speech.done: an unread body can't return its connection to the pool.
async for event in stream:
if isinstance(event, SpeechStreamEvent_SpeechChunk):
if event.audio:
audio = base64.b64decode(event.audio)
output_emitter.push(audio)
pushed += len(audio)
if event.speech_marks:
timed = _marks_to_timed(event.speech_marks, offset)
if timed:
output_emitter.push_timed_transcript(timed)
elif isinstance(event, SpeechStreamEvent_SpeechDone):
output_emitter.report_usage(characters_count=event.billable_characters_count)
elif isinstance(event, SpeechStreamEvent_SpeechError):
raise APIError(
"Speechify returned a speech error",
kind="invalid_request",
detail=event.error.message,
)
return pushed
def _raise_from(e: Exception) -> None:
if isinstance(e, APIError):
raise e
if isinstance(e, ApiError):
detail = str(e.body) if e.body is not None else None
if e.status_code is None:
raise APIError("Speechify API error", kind="server", detail=detail) from None
raise APIStatusError(
"Speechify API error", status_code=e.status_code, detail=detail
) from None
if isinstance(e, asyncio.TimeoutError):
raise APITimeoutError() from None
# The SDK only recognizes httpx v1 errors from its own client. The client
# we own is httpx2, so connect and timeout failures arrive here unwrapped.
if isinstance(e, httpx.TimeoutException):
raise APITimeoutError() from e
if isinstance(e, (ConnectionError, httpx.TransportError)):
raise APIConnectionError() from e
raise e
class ChunkedStream(tts.ChunkedStream):
def __init__(
self,
*,
tts: TTS,
input_text: str,
conn_options: APIConnectOptions,
opts: _TTSOptions,
client: AsyncSpeechify,
) -> None:
super().__init__(tts=tts, input_text=input_text, conn_options=conn_options)
self._opts = opts
self._client = client
async def _run(self, output_emitter: tts.AudioEmitter) -> None:
output_emitter.initialize(
request_id=utils.shortuuid(),
sample_rate=SAMPLE_RATE,
num_channels=NUM_CHANNELS,
mime_type=MIME_TYPE,
)
try:
await _synthesize_text(
self._client,
self._input_text,
self._opts,
self._conn_options,
output_emitter,
offset=0.0,
)
output_emitter.flush()
except Exception as e:
_raise_from(e)
class SynthesizeStream(tts.SynthesizeStream):
def __init__(
self,
*,
tts: TTS,
conn_options: APIConnectOptions,
opts: _TTSOptions,
client: AsyncSpeechify,
) -> None:
super().__init__(tts=tts, conn_options=conn_options)
self._opts = opts
self._client = client
async def _run(self, output_emitter: tts.AudioEmitter) -> None:
request_id = utils.shortuuid()
output_emitter.initialize(
request_id=request_id,
sample_rate=SAMPLE_RATE,
num_channels=NUM_CHANNELS,
mime_type=MIME_TYPE,
stream=True,
)
output_emitter.start_segment(segment_id=request_id)
offset = 0.0
try:
async for data in self.input:
if isinstance(data, self.Flush):
continue
self.mark_started()
chunk_bytes = await _synthesize_text(
self._client,
data.text,
self._opts,
self._conn_options,
output_emitter,
offset=offset,
)
output_emitter.flush()
offset += chunk_bytes / (2 * SAMPLE_RATE * NUM_CHANNELS)
except Exception as e:
_raise_from(e)
output_emitter.end_segment()