HTTP TTS cache working #1
+14
-10
@@ -21,7 +21,7 @@ from fastapi.staticfiles import StaticFiles
|
|||||||
import httpx
|
import httpx
|
||||||
from openai import AsyncOpenAI
|
from openai import AsyncOpenAI
|
||||||
|
|
||||||
from app.tts_cache import TTSCache
|
from app.tts_cache import CacheIOError, TTSCache
|
||||||
from app.knowledge import KnowledgeBase, format_knowledge_context, resolve_knowledge_dir
|
from app.knowledge import KnowledgeBase, format_knowledge_context, resolve_knowledge_dir
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
@@ -856,14 +856,13 @@ class VoiceSession:
|
|||||||
"similarity_boost": settings.elevenlabs_tts_similarity_boost,
|
"similarity_boost": settings.elevenlabs_tts_similarity_boost,
|
||||||
}
|
}
|
||||||
|
|
||||||
# Generate key & fetch lock dedicated ONLY to specific text/voice config
|
|
||||||
key = tts_cache._generate_key(**cache_params)
|
key = tts_cache._generate_key(**cache_params)
|
||||||
lock = await tts_cache.get_lock(key)
|
|
||||||
|
|
||||||
async with lock:
|
# Clean context manager handles acquisition, locking, and resource release automatically
|
||||||
|
async with tts_cache.lock(key):
|
||||||
# Check cache
|
# Check cache
|
||||||
|
try:
|
||||||
cached_audio = await tts_cache.get(**cache_params)
|
cached_audio = await tts_cache.get(**cache_params)
|
||||||
|
|
||||||
if cached_audio:
|
if cached_audio:
|
||||||
logger.info("Using cached TTS audio for text: %s", prepared_text[:30])
|
logger.info("Using cached TTS audio for text: %s", prepared_text[:30])
|
||||||
await self.send_json(
|
await self.send_json(
|
||||||
@@ -876,8 +875,10 @@ class VoiceSession:
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Failed to read TTS cache: %s", exc)
|
||||||
|
|
||||||
# Miss: Only ONE request per unique key executes the API call
|
# Miss (Executed only once across concurrent tasks for this key)
|
||||||
logger.info(
|
logger.info(
|
||||||
"Calling ElevenLabs HTTP TTS: model=%s voice_id=%s language=%s",
|
"Calling ElevenLabs HTTP TTS: model=%s voice_id=%s language=%s",
|
||||||
settings.elevenlabs_tts_model,
|
settings.elevenlabs_tts_model,
|
||||||
@@ -911,16 +912,19 @@ class VoiceSession:
|
|||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|
||||||
# Put in cache
|
# Isolated write: I/O disk failures will not disrupt returning audio to user
|
||||||
|
try:
|
||||||
await tts_cache.put(audio_data=response.content, **cache_params)
|
await tts_cache.put(audio_data=response.content, **cache_params)
|
||||||
|
except CacheIOError as exc:
|
||||||
|
logger.error("Failed to write TTS audio to cache: %s", exc)
|
||||||
|
|
||||||
await self.send_json(
|
await self.send_json(
|
||||||
{
|
{
|
||||||
"type": "tts_audio",
|
"type": "tts_audio",
|
||||||
"audio": base64.b64encode(response.content).decode("ascii"),
|
"audio": base64.b64encode(response.content).decode("ascii"),
|
||||||
"format": audio_format_label(settings.elevenlabs_tts_output_format),
|
"format": audio_format_label(output_format),
|
||||||
"sample_rate": audio_sample_rate(settings.elevenlabs_tts_output_format),
|
"sample_rate": audio_sample_rate(output_format),
|
||||||
"mime_type": audio_mime_type(settings.elevenlabs_tts_output_format),
|
"mime_type": audio_mime_type(output_format),
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
except httpx.HTTPStatusError as exc:
|
except httpx.HTTPStatusError as exc:
|
||||||
|
|||||||
+18
-2
@@ -2,6 +2,7 @@ import asyncio
|
|||||||
import hashlib
|
import hashlib
|
||||||
import logging
|
import logging
|
||||||
import tempfile
|
import tempfile
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
@@ -88,6 +89,23 @@ class TTSCache:
|
|||||||
self._key_locks[key] = asyncio.Lock()
|
self._key_locks[key] = asyncio.Lock()
|
||||||
return self._key_locks[key]
|
return self._key_locks[key]
|
||||||
|
|
||||||
|
async def release_lock(self, key: str) -> None:
|
||||||
|
"""Removes lock from dictionary if unreferenced."""
|
||||||
|
async with self._global_lock:
|
||||||
|
lock = self._key_locks.get(key)
|
||||||
|
if lock and not lock.locked():
|
||||||
|
self._key_locks.pop(key, None)
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lock(self, key: str):
|
||||||
|
"""Context manager for key-level deduplication that cleans up lock resources safely."""
|
||||||
|
lock_obj = await self.get_lock(key)
|
||||||
|
try:
|
||||||
|
async with lock_obj:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
await self.release_lock(key)
|
||||||
|
|
||||||
async def get(
|
async def get(
|
||||||
self,
|
self,
|
||||||
text: str,
|
text: str,
|
||||||
@@ -144,7 +162,6 @@ class TTSCache:
|
|||||||
try:
|
try:
|
||||||
await asyncio.to_thread(self.cache_dir.mkdir, parents=True, exist_ok=True)
|
await asyncio.to_thread(self.cache_dir.mkdir, parents=True, exist_ok=True)
|
||||||
|
|
||||||
# Atomic file write
|
|
||||||
def _atomic_write():
|
def _atomic_write():
|
||||||
with tempfile.NamedTemporaryFile(
|
with tempfile.NamedTemporaryFile(
|
||||||
dir=self.cache_dir,
|
dir=self.cache_dir,
|
||||||
@@ -186,7 +203,6 @@ class TTSCache:
|
|||||||
):
|
):
|
||||||
return
|
return
|
||||||
|
|
||||||
# Sort files by access time ascending (oldest first)
|
|
||||||
files.sort(key=lambda f: f.stat().st_atime)
|
files.sort(key=lambda f: f.stat().st_atime)
|
||||||
|
|
||||||
for f in files:
|
for f in files:
|
||||||
|
|||||||
Reference in New Issue
Block a user