HTTP TTS cache working #1
+77
-74
@@ -846,87 +846,90 @@ class VoiceSession:
|
|||||||
tts_language = resolve_tts_language(language_code)
|
tts_language = resolve_tts_language(language_code)
|
||||||
prepared_text = prepare_tts_text(text, tts_language)
|
prepared_text = prepare_tts_text(text, tts_language)
|
||||||
output_format = settings.elevenlabs_tts_output_format
|
output_format = settings.elevenlabs_tts_output_format
|
||||||
|
|
||||||
# Check if audio in cache
|
cache_params = {
|
||||||
cached_audio = tts_cache.get(text=prepared_text,
|
|
||||||
voice_id=voice_id,
|
|
||||||
output_format=output_format,
|
|
||||||
model_id=settings.elevenlabs_tts_model,
|
|
||||||
stability=settings.elevenlabs_tts_stability,
|
|
||||||
similarity_boost=settings.elevenlabs_tts_similarity_boost)
|
|
||||||
|
|
||||||
# cached audio found
|
|
||||||
if cached_audio:
|
|
||||||
logger.info("Using cached TTS audio for text: %s", prepared_text[:30])
|
|
||||||
await self.send_json(
|
|
||||||
{
|
|
||||||
"type": "tts_audio",
|
|
||||||
"audio": base64.b64encode(cached_audio).decode("ascii"),
|
|
||||||
"format": audio_format_label(output_format),
|
|
||||||
"sample_rate": audio_sample_rate(output_format),
|
|
||||||
"mime_type": audio_mime_type(output_format),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"Calling ElevenLabs HTTP TTS: model=%s voice_id=%s language=%s",
|
|
||||||
settings.elevenlabs_tts_model,
|
|
||||||
voice_id,
|
|
||||||
tts_language or "auto",
|
|
||||||
)
|
|
||||||
params = {"output_format": output_format}
|
|
||||||
payload: dict[str, Any] = {
|
|
||||||
"text": prepared_text,
|
"text": prepared_text,
|
||||||
|
"voice_id": voice_id,
|
||||||
|
"output_format": output_format,
|
||||||
"model_id": settings.elevenlabs_tts_model,
|
"model_id": settings.elevenlabs_tts_model,
|
||||||
"voice_settings": {
|
"stability": settings.elevenlabs_tts_stability,
|
||||||
"stability": settings.elevenlabs_tts_stability,
|
"similarity_boost": settings.elevenlabs_tts_similarity_boost,
|
||||||
"similarity_boost": settings.elevenlabs_tts_similarity_boost,
|
|
||||||
"use_speaker_boost": False,
|
|
||||||
"speed": settings.elevenlabs_tts_speed,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
if tts_language:
|
|
||||||
payload["language_code"] = tts_language
|
|
||||||
|
|
||||||
try:
|
# Generate key & fetch lock dedicated ONLY to specific text/voice config
|
||||||
async with httpx.AsyncClient(timeout=60.0) as client:
|
key = tts_cache._generate_key(**cache_params)
|
||||||
response = await client.post(
|
lock = await tts_cache.get_lock(key)
|
||||||
f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}",
|
|
||||||
params=params,
|
async with lock:
|
||||||
headers={
|
# Check cache
|
||||||
"xi-api-key": settings.elevenlabs_api_key or "",
|
cached_audio = await tts_cache.get(**cache_params)
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
if cached_audio:
|
||||||
json=payload,
|
logger.info("Using cached TTS audio for text: %s", prepared_text[:30])
|
||||||
|
await self.send_json(
|
||||||
|
{
|
||||||
|
"type": "tts_audio",
|
||||||
|
"audio": base64.b64encode(cached_audio).decode("ascii"),
|
||||||
|
"format": audio_format_label(output_format),
|
||||||
|
"sample_rate": audio_sample_rate(output_format),
|
||||||
|
"mime_type": audio_mime_type(output_format),
|
||||||
|
}
|
||||||
)
|
)
|
||||||
response.raise_for_status()
|
return
|
||||||
|
|
||||||
# put audio in cache
|
|
||||||
tts_cache.put(text=prepared_text,
|
|
||||||
voice_id=voice_id,
|
|
||||||
output_format=output_format,
|
|
||||||
audio_data=response.content,
|
|
||||||
model_id=settings.elevenlabs_tts_model,
|
|
||||||
stability=settings.elevenlabs_tts_stability,
|
|
||||||
similarity_boost=settings.elevenlabs_tts_similarity_boost)
|
|
||||||
|
|
||||||
await self.send_json(
|
# Miss: Only ONE request per unique key executes the API call
|
||||||
{
|
logger.info(
|
||||||
"type": "tts_audio",
|
"Calling ElevenLabs HTTP TTS: model=%s voice_id=%s language=%s",
|
||||||
"audio": base64.b64encode(response.content).decode("ascii"),
|
settings.elevenlabs_tts_model,
|
||||||
"format": audio_format_label(settings.elevenlabs_tts_output_format),
|
voice_id,
|
||||||
"sample_rate": audio_sample_rate(settings.elevenlabs_tts_output_format),
|
tts_language or "auto",
|
||||||
"mime_type": audio_mime_type(settings.elevenlabs_tts_output_format),
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
except httpx.HTTPStatusError as exc:
|
params = {"output_format": output_format}
|
||||||
message = exc.response.text[:500] if exc.response is not None else str(exc)
|
payload: dict[str, Any] = {
|
||||||
await self.send_tts_failed(
|
"text": prepared_text,
|
||||||
f"ElevenLabs HTTP TTS error: {exc.response.status_code} {message}"
|
"model_id": settings.elevenlabs_tts_model,
|
||||||
)
|
"voice_settings": {
|
||||||
except Exception as exc:
|
"stability": settings.elevenlabs_tts_stability,
|
||||||
await self.send_tts_failed(f"ElevenLabs HTTP TTS error: {exc}")
|
"similarity_boost": settings.elevenlabs_tts_similarity_boost,
|
||||||
|
"use_speaker_boost": False,
|
||||||
|
"speed": settings.elevenlabs_tts_speed,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if tts_language:
|
||||||
|
payload["language_code"] = tts_language
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(timeout=60.0) as client:
|
||||||
|
response = await client.post(
|
||||||
|
f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}",
|
||||||
|
params=params,
|
||||||
|
headers={
|
||||||
|
"xi-api-key": settings.elevenlabs_api_key or "",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
json=payload,
|
||||||
|
)
|
||||||
|
response.raise_for_status()
|
||||||
|
|
||||||
|
# Put in cache
|
||||||
|
await tts_cache.put(audio_data=response.content, **cache_params)
|
||||||
|
|
||||||
|
await self.send_json(
|
||||||
|
{
|
||||||
|
"type": "tts_audio",
|
||||||
|
"audio": base64.b64encode(response.content).decode("ascii"),
|
||||||
|
"format": audio_format_label(settings.elevenlabs_tts_output_format),
|
||||||
|
"sample_rate": audio_sample_rate(settings.elevenlabs_tts_output_format),
|
||||||
|
"mime_type": audio_mime_type(settings.elevenlabs_tts_output_format),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
except httpx.HTTPStatusError as exc:
|
||||||
|
message = exc.response.text[:500] if exc.response is not None else str(exc)
|
||||||
|
await self.send_tts_failed(
|
||||||
|
f"ElevenLabs HTTP TTS error: {exc.response.status_code} {message}"
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
await self.send_tts_failed(f"ElevenLabs HTTP TTS error: {exc}")
|
||||||
|
|
||||||
async def stream_tts(
|
async def stream_tts(
|
||||||
self,
|
self,
|
||||||
|
|||||||
+143
-22
@@ -1,14 +1,62 @@
|
|||||||
|
import asyncio
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import logging
|
||||||
|
import tempfile
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
DEFAULT_MAX_CACHE_BYTES = 500 * 1024 * 1024 # max 500 MB
|
||||||
|
DEFAULT_MAX_CACHE_FILES = 1000 # Max 1000 files in cache
|
||||||
|
DEFAULT_CACHE_DIR = ".tts_cache"
|
||||||
|
|
||||||
|
|
||||||
|
class CacheError(Exception):
|
||||||
|
"""Base exception for cache issues."""
|
||||||
|
|
||||||
|
|
||||||
|
class CacheIOError(CacheError):
|
||||||
|
"""Raised when reading or writing to cache fails."""
|
||||||
|
|
||||||
|
|
||||||
class TTSCache:
|
class TTSCache:
|
||||||
"""In-disk audio caching mechanism for ElevenLabs TTS requests."""
|
"""Simple in-disk audio cache with atomic writes, LRU eviction, and request locks."""
|
||||||
|
|
||||||
def __init__(self, cache_dir: str = ".tts_cache"):
|
def __init__(
|
||||||
|
self,
|
||||||
|
cache_dir: str = DEFAULT_CACHE_DIR,
|
||||||
|
max_bytes: int = DEFAULT_MAX_CACHE_BYTES,
|
||||||
|
max_files: Optional[int] = DEFAULT_MAX_CACHE_FILES,
|
||||||
|
):
|
||||||
self.cache_dir = Path(cache_dir)
|
self.cache_dir = Path(cache_dir)
|
||||||
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
self.max_bytes = max_bytes
|
||||||
|
self.max_files = max_files
|
||||||
|
|
||||||
|
# In-memory locks to prevent multiple concurrent tasks from writing/fetching the same key
|
||||||
|
self._key_locks: dict[str, asyncio.Lock] = {}
|
||||||
|
self._global_lock = asyncio.Lock()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def create(
|
||||||
|
cls,
|
||||||
|
cache_dir: str = DEFAULT_CACHE_DIR,
|
||||||
|
max_bytes: int = DEFAULT_MAX_CACHE_BYTES,
|
||||||
|
max_files: Optional[int] = DEFAULT_MAX_CACHE_FILES,
|
||||||
|
) -> "TTSCache":
|
||||||
|
"""Async factory method to ensure the cache directory exists."""
|
||||||
|
instance = cls(cache_dir, max_bytes=max_bytes, max_files=max_files)
|
||||||
|
try:
|
||||||
|
await asyncio.to_thread(
|
||||||
|
instance.cache_dir.mkdir, parents=True, exist_ok=True
|
||||||
|
)
|
||||||
|
logger.info("TTSCache directory ready at: %s", instance.cache_dir.resolve())
|
||||||
|
except (PermissionError, OSError) as e:
|
||||||
|
logger.critical(
|
||||||
|
"Failed to create cache directory [%s]: %s", instance.cache_dir, e
|
||||||
|
)
|
||||||
|
raise CacheIOError(f"Cannot initialize cache directory: {e}") from e
|
||||||
|
return instance
|
||||||
|
|
||||||
def _generate_key(
|
def _generate_key(
|
||||||
self,
|
self,
|
||||||
@@ -19,7 +67,6 @@ class TTSCache:
|
|||||||
stability: float = 0.5,
|
stability: float = 0.5,
|
||||||
similarity_boost: float = 0.75,
|
similarity_boost: float = 0.75,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Generates a deterministic unique hash for a TTS request configuration."""
|
|
||||||
raw_payload = (
|
raw_payload = (
|
||||||
f"{text.strip()}|{voice_id}|{output_format}|"
|
f"{text.strip()}|{voice_id}|{output_format}|"
|
||||||
f"{model_id}|{stability:.2f}|{similarity_boost:.2f}"
|
f"{model_id}|{stability:.2f}|{similarity_boost:.2f}"
|
||||||
@@ -27,14 +74,21 @@ class TTSCache:
|
|||||||
return hashlib.sha256(raw_payload.encode("utf-8")).hexdigest()
|
return hashlib.sha256(raw_payload.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
def get_extension(self, output_format: str) -> str:
|
def get_extension(self, output_format: str) -> str:
|
||||||
"""Determines file extension based on ElevenLabs output format."""
|
fmt = output_format.lower()
|
||||||
if "pcm" in output_format.lower():
|
if "pcm" in fmt:
|
||||||
return "pcm"
|
return "pcm"
|
||||||
elif "wav" in output_format.lower():
|
if "wav" in fmt:
|
||||||
return "wav"
|
return "wav"
|
||||||
return "mp3"
|
return "mp3"
|
||||||
|
|
||||||
def get(
|
async def get_lock(self, key: str) -> asyncio.Lock:
|
||||||
|
"""Retrieves or creates a dedicated asyncio.Lock for a given cache key."""
|
||||||
|
async with self._global_lock:
|
||||||
|
if key not in self._key_locks:
|
||||||
|
self._key_locks[key] = asyncio.Lock()
|
||||||
|
return self._key_locks[key]
|
||||||
|
|
||||||
|
async def get(
|
||||||
self,
|
self,
|
||||||
text: str,
|
text: str,
|
||||||
voice_id: str,
|
voice_id: str,
|
||||||
@@ -43,23 +97,30 @@ class TTSCache:
|
|||||||
stability: float = 0.5,
|
stability: float = 0.5,
|
||||||
similarity_boost: float = 0.75,
|
similarity_boost: float = 0.75,
|
||||||
) -> Optional[bytes]:
|
) -> Optional[bytes]:
|
||||||
"""Retrieves cached audio bytes if available, else returns None."""
|
"""Retrieves cached audio bytes if available."""
|
||||||
key = self._generate_key(
|
key = self._generate_key(
|
||||||
text, voice_id, output_format, model_id, stability, similarity_boost
|
text, voice_id, output_format, model_id, stability, similarity_boost
|
||||||
)
|
)
|
||||||
ext = self.get_extension(output_format)
|
ext = self.get_extension(output_format)
|
||||||
file_path = self.cache_dir / f"{key}.{ext}"
|
file_path = self.cache_dir / f"{key}.{ext}"
|
||||||
|
|
||||||
if file_path.exists():
|
try:
|
||||||
try:
|
exists = await asyncio.to_thread(file_path.exists)
|
||||||
with open(file_path, "rb") as f:
|
if exists:
|
||||||
return f.read()
|
# Update timestamp for LRU tracking
|
||||||
except Exception as e:
|
await asyncio.to_thread(file_path.touch, exist_ok=True)
|
||||||
print(f"[TTSCache] Failed to read cached file {file_path}: {e}")
|
data = await asyncio.to_thread(file_path.read_bytes)
|
||||||
return None
|
logger.debug("Cache HIT [%s]", key[:8])
|
||||||
|
return data
|
||||||
|
except (PermissionError, FileNotFoundError) as e:
|
||||||
|
logger.warning("File access issue during cache read [%s]: %s", file_path, e)
|
||||||
|
except OSError as e:
|
||||||
|
logger.error("OS error reading cache file [%s]: %s", file_path, e)
|
||||||
|
|
||||||
|
logger.debug("Cache MISS [%s]", key[:8])
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def put(
|
async def put(
|
||||||
self,
|
self,
|
||||||
text: str,
|
text: str,
|
||||||
voice_id: str,
|
voice_id: str,
|
||||||
@@ -69,7 +130,11 @@ class TTSCache:
|
|||||||
stability: float = 0.5,
|
stability: float = 0.5,
|
||||||
similarity_boost: float = 0.75,
|
similarity_boost: float = 0.75,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Saves generated audio bytes into the disk cache."""
|
"""Saves audio bytes atomically into the disk cache and triggers LRU cleanup."""
|
||||||
|
if not audio_data:
|
||||||
|
logger.warning("Attempted to cache empty bytes. Skipping.")
|
||||||
|
return
|
||||||
|
|
||||||
key = self._generate_key(
|
key = self._generate_key(
|
||||||
text, voice_id, output_format, model_id, stability, similarity_boost
|
text, voice_id, output_format, model_id, stability, similarity_boost
|
||||||
)
|
)
|
||||||
@@ -77,7 +142,63 @@ class TTSCache:
|
|||||||
file_path = self.cache_dir / f"{key}.{ext}"
|
file_path = self.cache_dir / f"{key}.{ext}"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(file_path, "wb") as f:
|
await asyncio.to_thread(self.cache_dir.mkdir, parents=True, exist_ok=True)
|
||||||
f.write(audio_data)
|
|
||||||
except Exception as e:
|
# Atomic file write
|
||||||
print(f"[TTSCache] Failed to write to cache {file_path}: {e}")
|
def _atomic_write():
|
||||||
|
with tempfile.NamedTemporaryFile(
|
||||||
|
dir=self.cache_dir,
|
||||||
|
prefix=f".tmp_{key}_",
|
||||||
|
suffix=f".{ext}",
|
||||||
|
delete=False,
|
||||||
|
) as tmp_file:
|
||||||
|
tmp_file.write(audio_data)
|
||||||
|
tmp_path = Path(tmp_file.name)
|
||||||
|
tmp_path.replace(file_path)
|
||||||
|
|
||||||
|
await asyncio.to_thread(_atomic_write)
|
||||||
|
logger.info("Cached audio [%s] (%d bytes)", key[:8], len(audio_data))
|
||||||
|
|
||||||
|
except (PermissionError, OSError) as e:
|
||||||
|
logger.error("Failed atomic write to cache [%s]: %s", file_path, e)
|
||||||
|
raise CacheIOError(f"Failed to write audio cache: {e}") from e
|
||||||
|
|
||||||
|
# Cleanup LRU asynchronously
|
||||||
|
await asyncio.to_thread(self._evict_lru)
|
||||||
|
|
||||||
|
def _evict_lru(self) -> None:
|
||||||
|
"""Removes the least recently accessed files when limits are breached."""
|
||||||
|
try:
|
||||||
|
files = [
|
||||||
|
f
|
||||||
|
for f in self.cache_dir.iterdir()
|
||||||
|
if f.is_file() and not f.name.startswith(".tmp_")
|
||||||
|
]
|
||||||
|
except (PermissionError, OSError) as e:
|
||||||
|
logger.error("Failed to inspect cache directory for LRU eviction: %s", e)
|
||||||
|
return
|
||||||
|
|
||||||
|
total_size = sum(f.stat().st_size for f in files)
|
||||||
|
total_count = len(files)
|
||||||
|
|
||||||
|
if total_size <= self.max_bytes and (
|
||||||
|
self.max_files is None or total_count <= self.max_files
|
||||||
|
):
|
||||||
|
return
|
||||||
|
|
||||||
|
# Sort files by access time ascending (oldest first)
|
||||||
|
files.sort(key=lambda f: f.stat().st_atime)
|
||||||
|
|
||||||
|
for f in files:
|
||||||
|
if total_size <= self.max_bytes and (
|
||||||
|
self.max_files is None or total_count <= self.max_files
|
||||||
|
):
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
f_size = f.stat().st_size
|
||||||
|
f.unlink(missing_ok=True)
|
||||||
|
total_size -= f_size
|
||||||
|
total_count -= 1
|
||||||
|
logger.info("Evicted LRU file: %s (%d bytes)", f.name, f_size)
|
||||||
|
except OSError as e:
|
||||||
|
logger.warning("Failed to evict file %s: %s", f, e)
|
||||||
|
|||||||
Reference in New Issue
Block a user