[Frontend] Speaker embedding support for speech and voices APIs (#1227)

Signed-off-by: marksverdhei <marksverdhei@hotmail.com>
Signed-off-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
Signed-off-by: linyueqian <linyueqian@outlook.com>
Co-authored-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
Co-authored-by: linyueqian <linyueqian@outlook.com>
This commit is contained in:
authored and GitHub committed 2026-03-25 19:02:48 +00:00
1 parent d2b9f9ff0f
commit 29936a3edd
10 files changed
+1093 -23

No files matched your search

+28 -8
View File
@@ -1024,6 +1024,8 @@ async def list_voices(raw_request: Request):
"created_at": info.get("created_at", 0),
"file_size": info.get("file_size", 0),
"mime_type": info.get("mime_type", ""),
"embedding_source": info.get("embedding_source", "audio"),
"embedding_dim": info.get("embedding_dim"),
}
)
@@ -1040,18 +1042,26 @@ async def list_voices(raw_request: Request):
)
async def upload_voice(
raw_request: Request,
audio_sample: UploadFile = File(...),
audio_sample: UploadFile | None = File(None),
speaker_embedding: str | None = Form(None),
consent: str = Form(...),
name: str = Form(...),
):
"""Upload a new voice sample for voice cloning.
"""Upload a new voice for voice cloning.
Uploads an audio file that can be used as a reference for voice cloning
in Base task TTS requests. The voice can then be referenced by name
in subsequent TTS requests.
Accepts either an audio file or a pre-computed speaker embedding vector.
These are mutually exclusive: provide one or the other.
When using ``audio_sample``, the server stores the audio and extracts the
speaker embedding on first use (Base task models only).
When using ``speaker_embedding``, pass a JSON-encoded list of floats
(1024-dim for 0.6B, 2048-dim for 1.7B). The voice is stored as a
safetensors file and is immediately ready for use.
Args:
audio_sample: Audio file (max 10MB)
audio_sample: Audio file (max 10MB). Mutually exclusive with speaker_embedding.
speaker_embedding: JSON-encoded float list. Mutually exclusive with audio_sample.
consent: Consent recording ID
name: Name for the new voice
raw_request: Raw FastAPI request
@@ -1064,8 +1074,18 @@ async def upload_voice(
return base(raw_request).create_error_response(message="The model does not support Speech API")
try:
# Upload the voice
result = await handler.upload_voice(audio_sample, consent, name)
if speaker_embedding is not None and audio_sample is not None:
return base(raw_request).create_error_response(
message="'audio_sample' and 'speaker_embedding' are mutually exclusive"
)
if speaker_embedding is not None:
result = await handler.upload_voice_embedding(speaker_embedding, consent, name)
elif audio_sample is not None:
result = await handler.upload_voice(audio_sample, consent, name)
else:
return base(raw_request).create_error_response(
message="Either 'audio_sample' or 'speaker_embedding' must be provided"
)
return JSONResponse(content={"success": True, "voice": result})
+30 -1
View File
@@ -1,8 +1,11 @@
import math
from typing import Literal
import numpy as np
from pydantic import BaseModel, Field, field_validator, model_validator
_MAX_EMBEDDING_DIM = 8192
class OpenAICreateSpeechRequest(BaseModel):
input: str
@@ -41,7 +44,7 @@ class OpenAICreateSpeechRequest(BaseModel):
)
ref_audio: str | None = Field(
default=None,
description="Reference audio for voice cloning (Base task). URL, base64, or file path.",
description="Reference audio for voice cloning (Base task). URL, base64, or file URI.",
)
ref_text: str | None = Field(
default=None,
@@ -51,6 +54,13 @@ class OpenAICreateSpeechRequest(BaseModel):
default=None,
description="Use speaker embedding only without in-context learning (Base task)",
)
speaker_embedding: list[float] | None = Field(
default=None,
max_length=_MAX_EMBEDDING_DIM,
description="Pre-computed speaker embedding vector (1024-dim for 0.6B, "
"2048-dim for 1.7B). Skips speaker encoder extraction from ref_audio. "
"Implies x_vector_only_mode=True. Mutually exclusive with ref_audio.",
)
max_new_tokens: int | None = Field(
default=None,
description="Maximum tokens to generate",
@@ -68,6 +78,20 @@ class OpenAICreateSpeechRequest(BaseModel):
raise ValueError("'sse' is not a supported stream_format yet. Please use 'audio'.")
return v
@field_validator("speaker_embedding")
@classmethod
def validate_speaker_embedding(cls, v: list[float] | None) -> list[float] | None:
if v is not None and not all(math.isfinite(x) for x in v):
raise ValueError("'speaker_embedding' values must be finite (no NaN or Inf)")
return v
@model_validator(mode="after")
def validate_embedding_constraints(self) -> "OpenAICreateSpeechRequest":
if self.speaker_embedding is not None:
if self.ref_audio is not None:
raise ValueError("'speaker_embedding' and 'ref_audio' are mutually exclusive")
return self
@model_validator(mode="after")
def validate_streaming_constraints(self) -> "OpenAICreateSpeechRequest":
if self.stream:
@@ -177,6 +201,11 @@ class StreamingSpeechSessionConfig(BaseModel):
ref_audio: str | None = None
ref_text: str | None = None
x_vector_only_mode: bool | None = None
speaker_embedding: list[float] | None = Field(
default=None,
max_length=_MAX_EMBEDDING_DIM,
description="Pre-computed speaker embedding vector. Mutually exclusive with ref_audio.",
)
stream_audio: bool = Field(
default=False,
description=(
+139 -9
View File
@@ -532,6 +532,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
"cache_status": "pending", # The initial cache state is pending.
"cache_file": None, # The initial cache file is empty.
"cache_generated_at": None, # The initial cache generation time is empty.
"embedding_source": "audio",
}
# Save metadata using metadata manager (concurrency safe)
@@ -559,6 +560,101 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
"file_size": file_size,
}
async def upload_voice_embedding(self, embedding_json: str, consent: str, name: str) -> dict:
"""Upload a voice from a pre-computed speaker embedding.
Stores the embedding as a safetensors file and marks it immediately
ready (no audio processing needed).
Args:
embedding_json: JSON-encoded list of floats (1024 or 2048 dim).
consent: Consent recording ID.
name: Name for the new voice.
Returns:
dict with voice information.
"""
try:
embedding = json.loads(embedding_json)
except (json.JSONDecodeError, TypeError) as exc:
raise ValueError(f"'speaker_embedding' must be valid JSON: {exc}") from exc
if not isinstance(embedding, list) or not embedding:
raise ValueError("'speaker_embedding' must be a non-empty list of numbers")
if not all(isinstance(x, (int, float)) for x in embedding):
raise ValueError("'speaker_embedding' must contain only numeric values")
if not all(math.isfinite(x) for x in embedding):
raise ValueError("'speaker_embedding' values must be finite (no NaN or Inf)")
emb_dim = len(embedding)
if emb_dim not in {1024, 2048}:
logger.warning(
"speaker_embedding has %d dimensions; expected 1024 (0.6B) or 2048 (1.7B)",
emb_dim,
)
voice_name_lower = name.lower()
if voice_name_lower in self.uploaded_speakers:
raise ValueError(f"Voice '{name}' already exists")
sanitized_name = _sanitize_filename(name)
sanitized_consent = _sanitize_filename(consent)
timestamp = int(time.time())
# Store as safetensors for efficient loading
try:
import torch
from safetensors.torch import save_file
tensor = torch.tensor(embedding, dtype=torch.float32)
filename = f"{sanitized_name}_{sanitized_consent}_{timestamp}.safetensors"
file_path = self.uploaded_speakers_dir / filename
if not _validate_path_within_directory(file_path, self.uploaded_speakers_dir):
raise ValueError("Invalid file path: potential path traversal attack detected")
save_file({"speaker_embedding": tensor}, str(file_path))
except ImportError:
raise ValueError("safetensors and torch are required for embedding upload")
speaker_data = {
"name": name,
"consent": consent,
"file_path": str(file_path),
"created_at": timestamp,
"mime_type": "application/x-safetensors",
"original_filename": filename,
"file_size": file_path.stat().st_size,
"cache_status": "ready",
"cache_file": str(file_path),
"cache_generated_at": timestamp,
"embedding_source": "direct",
"embedding_dim": emb_dim,
}
success = self.metadata_manager.create_speaker(voice_name_lower, speaker_data)
if not success:
try:
file_path.unlink()
except Exception:
pass
raise ValueError(f"Failed to create metadata for voice '{name}' (possibly already exists)")
self.uploaded_speakers[voice_name_lower] = speaker_data
self.supported_speakers.add(voice_name_lower)
logger.info(f"Uploaded voice '{name}' from speaker embedding ({emb_dim}-dim)")
return {
"name": name,
"consent": consent,
"created_at": timestamp,
"embedding_source": "direct",
"embedding_dim": emb_dim,
}
async def delete_voice(self, name: str) -> bool:
"""
Delete an uploaded voice.
@@ -669,23 +765,46 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
if request.voice is not None and request.voice not in self.supported_speakers:
return f"Invalid voice '{request.voice}'. Supported: {', '.join(sorted(self.supported_speakers))}"
# Validate speaker_embedding constraints
if request.speaker_embedding is not None:
if task_type != "Base":
return "'speaker_embedding' is only valid for Base task"
if not request.speaker_embedding:
return "'speaker_embedding' must be a non-empty list of floats"
# speaker_embedding implies x_vector_only_mode — set it before
# Base task validation so callers don't need to pass it explicitly.
request.x_vector_only_mode = True
emb_len = len(request.speaker_embedding)
# ECAPA-TDNN produces 1024-dim (0.6B) or 2048-dim (1.7B)
expected_dims = {1024, 2048}
if emb_len not in expected_dims:
logger.warning(
"speaker_embedding has %d dimensions; expected 1024 "
"(0.6B model) or 2048 (1.7B model). Wrong dimensions "
"will likely result in errors or degraded quality.",
emb_len,
)
# Validate Base task requirements
if task_type == "Base":
if request.voice is None:
if request.ref_audio is None:
return "Base task requires 'ref_audio' for voice cloning"
fmt_err = self._validate_ref_audio_format(request.ref_audio)
if fmt_err:
return fmt_err
# In-context voice cloning (default) requires non-empty ref_text.
# x_vector_only_mode skips in-context and only uses speaker embedding.
if not request.x_vector_only_mode:
# 1. Ensure a voice source is provided
if request.ref_audio is None and getattr(request, "speaker_embedding", None) is None:
return "Base task requires 'ref_audio' or 'speaker_embedding' for voice cloning"
# 2. Validate ref_audio format if it exists (using the helper from main)
if request.ref_audio is not None:
fmt_err = self._validate_ref_audio_format(request.ref_audio)
if fmt_err:
return fmt_err
# 3. Validate text requirements based on the mode
if not getattr(request, "x_vector_only_mode", False):
if not request.ref_text or not request.ref_text.strip():
return (
"Base task requires non-empty 'ref_text' (transcript of "
"the reference audio) unless 'x_vector_only_mode' is enabled"
)
else:
# Handle the case where request.voice is NOT None
pass
# voice is not None
voice_lower = request.voice.lower()
if voice_lower in self.uploaded_speakers:
@@ -890,7 +1009,18 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
# Voice clone: ref_audio resolved in create_speech(), not here.
if request.ref_text is not None:
params["ref_text"] = [request.ref_text]
if request.x_vector_only_mode is not None:
if request.speaker_embedding is not None:
# Store as plain float list (not tensor) so it survives msgspec
# serialization through the EngineCore IPC boundary. The talker's
# _build_prompt_embeds converts it back to a tensor on the GPU.
params["voice_clone_prompt"] = [
{
"ref_spk_embedding": list(request.speaker_embedding),
}
]
# speaker_embedding implies x_vector_only_mode
params["x_vector_only_mode"] = [True]
elif request.x_vector_only_mode is not None:
params["x_vector_only_mode"] = [request.x_vector_only_mode]
# Generation parameters
@@ -224,6 +224,7 @@ class OmniStreamingSpeechHandler:
ref_audio=config.ref_audio,
ref_text=config.ref_text,
x_vector_only_mode=config.x_vector_only_mode,
speaker_embedding=config.speaker_embedding,
stream=config.stream_audio,
)