feat(tts): add voice upload API for Qwen3-TTS (#1201)

Signed-off-by: linyueqian <linyueqian@outlook.com>
Co-authored-by: linyueqian <linyueqian@outlook.com>
Co-authored-by: Yueqian Lin <70319226+linyueqian@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-03-09 11:02:11 +08:00
1 parent 382bbd0a1f
commit 41964cb90a
8 files changed
+1483 -53

No files matched your search

+106 -1
View File
@@ -881,8 +881,113 @@ async def list_voices(raw_request: Request):
if handler is None:
return base(raw_request).create_error_response(message="The model does not support Speech API")
# Get all speakers (both model built-in and uploaded)
speakers = sorted(handler.supported_speakers) if handler.supported_speakers else []
return JSONResponse(content={"voices": speakers})
# Get uploaded speakers details
uploaded_speakers = []
if hasattr(handler, "uploaded_speakers"):
for voice_name, info in handler.uploaded_speakers.items():
uploaded_speakers.append(
{
"name": info.get("name", voice_name),
"consent": info.get("consent", ""),
"created_at": info.get("created_at", 0),
"file_size": info.get("file_size", 0),
"mime_type": info.get("mime_type", ""),
}
)
return JSONResponse(content={"voices": speakers, "uploaded_voices": uploaded_speakers})
@router.post(
"/v1/audio/voices",
responses={
HTTPStatus.OK.value: {"model": dict},
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
},
)
async def upload_voice(
raw_request: Request,
audio_sample: UploadFile = File(...),
consent: str = Form(...),
name: str = Form(...),
):
"""Upload a new voice sample 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.
Args:
audio_sample: Audio file (max 10MB)
consent: Consent recording ID
name: Name for the new voice
raw_request: Raw FastAPI request
Returns:
JSON response with voice information
"""
handler = Omnispeech(raw_request)
if handler is None:
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)
return JSONResponse(content={"success": True, "voice": result})
except ValueError as e:
return base(raw_request).create_error_response(message=str(e))
except Exception as e:
logger.exception(f"Failed to upload voice: {e}")
return base(raw_request).create_error_response(message=f"Failed to upload voice: {str(e)}")
@router.delete(
"/v1/audio/voices/{name}",
responses={
HTTPStatus.OK.value: {"model": dict},
HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse},
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
},
)
async def delete_voice(name: str, raw_request: Request):
"""Delete an uploaded voice.
Deletes the voice sample and associated metadata. Also removes any
cached voice clone prompts for this voice.
Args:
name: Name of the voice to delete
raw_request: Raw FastAPI request
Returns:
JSON response indicating success or failure
"""
handler = Omnispeech(raw_request)
if handler is None:
return base(raw_request).create_error_response(message="The model does not support Speech API")
try:
# Delete the voice
success = await handler.delete_voice(name)
if not success:
return JSONResponse(
content={"success": False, "error": f"Voice '{name}' not found"},
status_code=HTTPStatus.NOT_FOUND.value,
)
return JSONResponse(content={"success": True, "message": f"Voice '{name}' deleted successfully"})
except ValueError as e:
return base(raw_request).create_error_response(message=str(e))
except Exception as e:
logger.exception(f"Failed to delete voice '{name}': {e}")
return base(raw_request).create_error_response(message=f"Failed to delete voice: {str(e)}")
# Health and Model endpoints for diffusion mode
@@ -0,0 +1,243 @@
"""
Metadata manager for voice samples and cache information.
Provides a unified interface for managing metadata.json with
concurrency safety and data consistency across multiple processes.
"""
import fcntl
import json
import logging
import os
import threading
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any
logger = logging.getLogger(__name__)
class MetadataManager:
"""
Manages metadata for uploaded speakers and cache information.
Features:
1. Single source of truth for metadata
2. Concurrency safety with threading locks
3. Atomic read-modify-write operations
4. Merge updates to preserve fields from different components
"""
def __init__(self, metadata_file: Path):
"""
Initialize the metadata manager.
Args:
metadata_file: Path to metadata.json file
"""
self.metadata_file = metadata_file
self._lock = threading.Lock() # For intra-process concurrency
self._metadata = self._load_from_disk()
# Create lock file for cross-process synchronization
self.lock_file = metadata_file.with_suffix(".lock")
self.lock_file.parent.mkdir(parents=True, exist_ok=True)
def _load_from_disk(self) -> dict[str, Any]:
"""Load metadata from disk."""
if not self.metadata_file.exists():
return {"uploaded_speakers": {}}
try:
with open(self.metadata_file) as f:
return json.load(f)
except Exception as e:
logger.error(f"Failed to load metadata from {self.metadata_file}: {e}")
return {"uploaded_speakers": {}}
def _save_to_disk(self, metadata: dict[str, Any]) -> bool:
"""Save metadata to disk."""
try:
self.metadata_file.parent.mkdir(parents=True, exist_ok=True)
tmp = self.metadata_file.with_suffix(".tmp")
with open(tmp, "w") as f:
json.dump(metadata, f, indent=2)
tmp.replace(self.metadata_file)
return True
except Exception as e:
logger.error(f"Failed to save metadata to {self.metadata_file}: {e}")
return False
# ================================
# Core fix: single flock overwrites RMW
# ================================
def _update_with_file_lock(
self, update_fn: Callable[[dict[str, Any]], dict[str, Any] | None]
) -> dict[str, Any] | None:
lock_fd = os.open(self.lock_file, os.O_CREAT | os.O_RDWR)
try:
fcntl.flock(lock_fd, fcntl.LOCK_EX)
metadata = self._load_from_disk()
result = update_fn(metadata)
if result is None:
return None
if not self._save_to_disk(metadata):
return None
self._metadata = metadata
return result
finally:
fcntl.flock(lock_fd, fcntl.LOCK_UN)
os.close(lock_fd)
def get_uploaded_speakers(self) -> dict[str, dict[str, Any]]:
"""Get all uploaded speakers."""
# Read directly from disk to ensure getting the latest data
metadata = self._load_from_disk()
return metadata.get("uploaded_speakers", {}).copy()
def get_speaker(self, speaker_key: str) -> dict[str, Any] | None:
"""Get specific speaker information."""
# Read directly from disk to ensure getting the latest data
metadata = self._load_from_disk()
speakers = metadata.get("uploaded_speakers", {})
return speakers.get(speaker_key, {}).copy() if speaker_key in speakers else None
def update_speaker(self, speaker_key: str, updates: dict[str, Any]) -> bool:
"""
Update speaker information with merge semantics.
Uses file locking for cross-process atomic operations.
"""
with self._lock:
def _update(metadata: dict[str, Any]):
speakers = metadata.setdefault("uploaded_speakers", {})
entry = speakers.get(speaker_key, {})
entry.update(updates)
speakers[speaker_key] = entry
return True
return self._update_with_file_lock(_update) is not None
def create_speaker(self, speaker_key: str, speaker_data: dict[str, Any]) -> bool:
"""
Create a new speaker entry.
Uses file locking for cross-process atomic operations.
"""
with self._lock:
def _create(metadata: dict[str, Any]):
speakers = metadata.setdefault("uploaded_speakers", {})
if speaker_key in speakers:
logger.warning(f"Speaker {speaker_key} already exists")
return None
speakers[speaker_key] = speaker_data
return True
return self._update_with_file_lock(_create) is not None
def update_cache_info(self, speaker_key: str, cache_file_path: Path, status: str = "ready") -> bool:
"""
Update cache information for a speaker.
"""
updates = {
"cache_status": status,
"cache_file": str(cache_file_path),
"cache_generated_at": time.time(),
}
return self.update_speaker(speaker_key, updates)
def delete_speaker(self, speaker_key: str) -> dict[str, Any] | None:
"""
Delete a speaker from metadata and clean up associated files.
Uses file locking for cross-process atomic operations.
Args:
speaker_key: Speaker name (lowercase)
base_dir: Base directory for file validation (optional)
Returns:
dict: Deleted speaker information if successful, None if speaker doesn't exist or error
"""
with self._lock:
def _delete(metadata: dict[str, Any]):
speakers = metadata.get("uploaded_speakers", {})
if speaker_key not in speakers:
logger.warning(f"Speaker {speaker_key} not found in metadata")
return None
speaker_info = speakers.pop(speaker_key)
# Clean up associated files
deleted_files = self._cleanup_speaker_files(speaker_info)
if deleted_files:
logger.info(f"Deleted {len(deleted_files)} files for speaker {speaker_key}: {deleted_files}")
return speaker_info
return self._update_with_file_lock(_delete)
def _cleanup_speaker_files(self, speaker_info: dict[str, Any]) -> list[str]:
"""
Clean up files associated with a speaker.
Args:
speaker_info: Speaker information dictionary
base_dir: Base directory for file validation (optional)
Returns:
list: List of successfully deleted file paths
"""
deleted_files = []
# Helper function to safely delete a file
def safe_delete(file_path_str: str, description: str) -> bool:
if not file_path_str:
return False
try:
file_path = Path(file_path_str)
# Check if file exists
if not file_path.exists():
logger.debug(f"{description} not found: {file_path}")
return False
# Delete the file
file_path.unlink()
logger.info(f"Deleted {description}: {file_path}")
deleted_files.append(str(file_path))
return True
except Exception as e:
logger.error(f"Failed to delete {description} {file_path_str}: {e}")
return False
# Delete audio file
audio_file = speaker_info.get("file_path")
if audio_file:
safe_delete(audio_file, "audio file")
# Delete cache file
cache_file = speaker_info.get("cache_file")
if cache_file:
safe_delete(cache_file, "cache file")
return deleted_files
def reload_from_disk(self) -> bool:
"""Force reload metadata from disk (useful for external changes)."""
with self._lock:
try:
self._metadata = self._load_from_disk()
return True
except Exception as e:
logger.error(f"Failed to reload metadata from disk: {e}")
return False
+295 -19
View File
@@ -1,11 +1,15 @@
import asyncio
import base64
import json
import math
import os
import re
import time
from pathlib import Path
from typing import Any
import numpy as np
from fastapi import Request
from fastapi import Request, UploadFile
from fastapi.responses import Response, StreamingResponse
from vllm.entrypoints.openai.engine.serving import OpenAIServing
from vllm.logger import init_logger
@@ -13,6 +17,7 @@ from vllm.multimodal.media import MediaConnector
from vllm.utils import random_uuid
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
from vllm_omni.entrypoints.openai.metadata_manager import MetadataManager
from vllm_omni.entrypoints.openai.protocol.audio import (
CreateAudio,
OpenAICreateSpeechRequest,
@@ -41,9 +46,52 @@ _TTS_MAX_NEW_TOKENS_MIN = 1
_TTS_MAX_NEW_TOKENS_MAX = 4096
def _sanitize_filename(filename: str) -> str:
"""Sanitize filename to prevent path traversal attacks.
Only allows alphanumeric characters, underscores, hyphens, and dots.
Replaces any other characters with underscores.
"""
# Remove any path components
filename = os.path.basename(filename)
# Replace any non-alphanumeric, underscore, hyphen, or dot with underscore
sanitized = re.sub(r"[^a-zA-Z0-9_.\-]", "_", filename)
# Ensure filename is not empty
if not sanitized:
sanitized = "file"
# Limit length to prevent potential issues
if len(sanitized) > 255:
sanitized = sanitized[:255]
return sanitized
def _validate_path_within_directory(file_path: Path, directory: Path) -> bool:
"""Validate that file_path is within the specified directory.
Prevents path traversal attacks by ensuring the resolved path
is within the target directory.
"""
try:
# Resolve both paths to absolute paths
file_path_resolved = file_path.resolve()
directory_resolved = directory.resolve()
# Check if file_path is within directory
return directory_resolved in file_path_resolved.parents or directory_resolved == file_path_resolved
except Exception:
return False
class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Initialize uploaded speakers storage
speech_voice_samples_dir = os.environ.get("SPEECH_VOICE_SAMPLES", "/tmp/voice_samples")
self.uploaded_speakers_dir = Path(speech_voice_samples_dir)
self.uploaded_speakers_dir.mkdir(parents=True, exist_ok=True)
self.metadata_file = self.uploaded_speakers_dir / "metadata.json"
# Initialize metadata manager
self.metadata_manager = MetadataManager(self.metadata_file)
# Find and cache the TTS stage (if any) during initialization
self._tts_stage = self._find_tts_stage()
@@ -54,9 +102,16 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
# Load supported speakers
self.supported_speakers = self._load_supported_speakers()
logger.info(f"Loaded {len(self.supported_speakers)} supported speakers: {sorted(self.supported_speakers)}")
# Load uploaded speakers
self.uploaded_speakers = self.metadata_manager.get_uploaded_speakers()
# Merge supported speakers with uploaded speakers
self.supported_speakers.update(self.uploaded_speakers.keys())
self._tts_tokenizer = None
logger.info(f"Loaded {len(self.supported_speakers)} supported speakers: {sorted(self.supported_speakers)}")
logger.info(f"Loaded {len(self.uploaded_speakers)} uploaded speakers")
# Load speech tokenizer codec parameters for prompt length estimation
self._codec_frame_rate: float | None = self._load_codec_frame_rate()
@@ -204,6 +259,191 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
logger.warning("Failed to estimate TTS prompt length, using fallback 2048: %s", e)
return 2048
def _get_uploaded_audio_data(self, voice_name: str) -> str | None:
"""Get base64 encoded audio data for uploaded voice."""
voice_name_lower = voice_name.lower()
if voice_name_lower not in self.uploaded_speakers:
return None
speaker_info = self.uploaded_speakers[voice_name_lower]
file_path = Path(speaker_info["file_path"])
if not file_path.exists():
logger.warning(f"Audio file not found for voice {voice_name}: {file_path}")
return None
try:
# Read audio file
with open(file_path, "rb") as f:
audio_bytes = f.read()
# Encode to base64
audio_b64 = base64.b64encode(audio_bytes).decode("utf-8")
# Get MIME type from file extension
mime_type = speaker_info.get("mime_type", "audio/wav")
# Return as data URL
return f"data:{mime_type};base64,{audio_b64}"
except Exception as e:
logger.error(f"Could not read audio file for voice {voice_name}: {e}")
return None
async def upload_voice(self, audio_file: UploadFile, consent: str, name: str) -> dict:
"""Upload a new voice sample."""
# Validate file size (max 10MB)
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
audio_file.file.seek(0, 2) # Seek to end
file_size = audio_file.file.tell()
audio_file.file.seek(0) # Reset to beginning
if file_size > MAX_FILE_SIZE:
raise ValueError(f"File size exceeds maximum limit of 10MB. Got {file_size} bytes.")
# Detect MIME type from filename if content_type is generic
mime_type = audio_file.content_type
if mime_type == "application/octet-stream":
# Simple MIME type detection based on file extension
filename_lower = audio_file.filename.lower()
if filename_lower.endswith(".wav"):
mime_type = "audio/wav"
elif filename_lower.endswith((".mp3", ".mpeg")):
mime_type = "audio/mpeg"
elif filename_lower.endswith(".flac"):
mime_type = "audio/flac"
elif filename_lower.endswith(".ogg"):
mime_type = "audio/ogg"
elif filename_lower.endswith(".aac"):
mime_type = "audio/aac"
elif filename_lower.endswith(".webm"):
mime_type = "audio/webm"
elif filename_lower.endswith(".mp4"):
mime_type = "audio/mp4"
else:
mime_type = "audio/wav" # Default
# Validate MIME type
allowed_mime_types = {
"audio/mpeg",
"audio/wav",
"audio/x-wav",
"audio/ogg",
"audio/aac",
"audio/flac",
"audio/webm",
"audio/mp4",
}
if mime_type not in allowed_mime_types:
raise ValueError(f"Unsupported MIME type: {mime_type}. Allowed: {allowed_mime_types}")
# Normalize voice name
voice_name_lower = name.lower()
# Check if voice already exists
if voice_name_lower in self.uploaded_speakers:
raise ValueError(f"Voice '{name}' already exists")
# Sanitize name and consent to prevent path traversal
sanitized_name = _sanitize_filename(name)
sanitized_consent = _sanitize_filename(consent)
# Generate filename with sanitized inputs
timestamp = int(time.time())
file_suffix = Path(audio_file.filename).suffix
file_ext = file_suffix[1:] if file_suffix and len(file_suffix) > 1 else "wav"
# Sanitize file extension as well
sanitized_ext = _sanitize_filename(file_ext)
if not sanitized_ext or sanitized_ext == "file":
sanitized_ext = "wav"
filename = f"{sanitized_name}_{sanitized_consent}_{timestamp}.{sanitized_ext}"
file_path = self.uploaded_speakers_dir / filename
# Double-check that the path is within the upload directory
if not _validate_path_within_directory(file_path, self.uploaded_speakers_dir):
raise ValueError("Invalid file path: potential path traversal attack detected")
# Save audio file
try:
with open(file_path, "wb") as f:
content = await audio_file.read()
f.write(content)
except Exception as e:
raise ValueError(f"Failed to save audio file: {e}")
# Create speaker data
speaker_data = {
"name": name,
"consent": consent,
"file_path": str(file_path),
"created_at": timestamp,
"mime_type": mime_type,
"original_filename": audio_file.filename,
"file_size": file_size,
"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.
}
# Save metadata using metadata manager (concurrency safe)
success = self.metadata_manager.create_speaker(voice_name_lower, speaker_data)
if not success:
# Clean up the saved file if metadata creation failed
try:
file_path.unlink()
except Exception:
pass
raise ValueError(f"Failed to create metadata for voice '{name}' (possibly already exists)")
# Update in-memory cache
self.uploaded_speakers[voice_name_lower] = speaker_data
self.supported_speakers.add(voice_name_lower)
logger.info(f"Uploaded new voice '{name}' with consent ID '{consent}'")
# Return voice information without exposing the server file path
return {
"name": name,
"consent": consent,
"created_at": timestamp,
"mime_type": mime_type,
"file_size": file_size,
}
async def delete_voice(self, name: str) -> bool:
"""
Delete an uploaded voice.
Args:
name: Voice name to delete
Returns:
bool: True if successful, False if voice doesn't exist
"""
voice_name_lower = name.lower()
# Check if voice exists in memory cache
if voice_name_lower not in self.uploaded_speakers:
logger.warning(f"Voice '{name}' not found in memory cache")
return False
# Delete from metadata manager with file cleanup
# Pass base_dir for path validation
deleted_info = self.metadata_manager.delete_speaker(voice_name_lower)
if not deleted_info:
logger.error(f"Failed to delete voice '{name}' from metadata")
return False
# Update in-memory cache
if voice_name_lower in self.uploaded_speakers:
del self.uploaded_speakers[voice_name_lower]
if voice_name_lower in self.supported_speakers:
self.supported_speakers.remove(voice_name_lower)
logger.info(f"Deleted voice '{name}' and associated files")
return True
def _is_tts_model(self) -> bool:
"""Check if the current model is a supported TTS model."""
stage_list = getattr(self.engine_client, "stage_list", None)
@@ -246,23 +486,48 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
# Validate Base task requirements
if task_type == "Base":
if request.ref_audio is None:
return "Base task requires 'ref_audio' for voice cloning"
# Validate ref_audio format
if not (
request.ref_audio.startswith(("http://", "https://"))
or request.ref_audio.startswith("data:")
or request.ref_audio.startswith("file://")
):
return "ref_audio must be a URL (http/https), base64 data URL (data:...), or file URI (file://...)"
# 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:
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"
)
if request.voice is None:
if request.ref_audio is None:
return "Base task requires 'ref_audio' for voice cloning"
# Validate ref_audio format (include file:// from upstream)
if not (
request.ref_audio.startswith(("http://", "https://"))
or request.ref_audio.startswith("data:")
or request.ref_audio.startswith("file://")
):
return "ref_audio must be a URL (http/https), base64 data URL (data:...), or file URI (file://...)"
# 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:
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:
# voice is not None
voice_lower = request.voice.lower()
if voice_lower in self.uploaded_speakers:
# Check if audio file exists for uploaded speaker
speaker_info = self.uploaded_speakers[voice_lower]
file_path = Path(speaker_info["file_path"])
if not file_path.exists():
return f"Audio file for uploaded speaker '{request.voice}' not found on disk"
else:
# need ref_audio for built-in speaker
if request.ref_audio is None:
return (
f"Base task with built-in speaker '{request.voice}' requires 'ref_audio' for voice cloning"
)
# Validate ref_audio format for built-in speaker
if not (
request.ref_audio.startswith(("http://", "https://"))
or request.ref_audio.startswith("data:")
or request.ref_audio.startswith("file://")
):
return (
"ref_audio must be a URL (http/https), base64 data URL (data:...), or file URI (file://...)"
)
# Validate cross-parameter dependencies
if task_type != "Base":
@@ -411,6 +676,17 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
# Speaker (voice)
if request.voice is not None:
params["speaker"] = [request.voice]
# If voice is an uploaded speaker and no ref_audio provided, auto-set it
if request.voice.lower() in self.uploaded_speakers and request.ref_audio is None:
audio_data = self._get_uploaded_audio_data(request.voice)
if audio_data:
params["ref_audio"] = [audio_data]
params["x_vector_only_mode"] = [True]
logger.info(f"Auto-set ref_audio for uploaded voice: {request.voice}")
else:
raise ValueError(f"Audio file for uploaded voice '{request.voice}' is missing or corrupted")
elif params["task_type"][0] == "CustomVoice":
params["speaker"] = ["Vivian"] # Default for CustomVoice