diff --git a/.gitignore b/.gitignore index 1dfd00d..4dc76ca 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,5 @@ __pycache__/ .env .DS_Store .playwright-mcp/ +# TTS Cache default directory +.tts_cache/ diff --git a/app/main.py b/app/main.py index a61103e..1a29ee2 100644 --- a/app/main.py +++ b/app/main.py @@ -21,10 +21,13 @@ from fastapi.staticfiles import StaticFiles import httpx from openai import AsyncOpenAI +from app.tts_cache import TTSCache from app.knowledge import KnowledgeBase, format_knowledge_context, resolve_knowledge_dir load_dotenv() +tts_cache = TTSCache(cache_dir=".tts_cache") + BASE_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_DIR = os.path.dirname(BASE_DIR) STATIC_DIR = os.path.join(BASE_DIR, "static") @@ -841,15 +844,40 @@ class VoiceSession: async def synthesize_tts_http(self, text: str, language_code: str | None = None) -> None: voice_id = settings.elevenlabs_voice_id tts_language = resolve_tts_language(language_code) + prepared_text = prepare_tts_text(text, tts_language) + output_format = settings.elevenlabs_tts_output_format + + # Check if audio in cache + 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": settings.elevenlabs_tts_output_format} + params = {"output_format": output_format} payload: dict[str, Any] = { - "text": prepare_tts_text(text, tts_language), + "text": prepared_text, "model_id": settings.elevenlabs_tts_model, "voice_settings": { "stability": settings.elevenlabs_tts_stability, @@ -873,6 +901,15 @@ class VoiceSession: json=payload, ) response.raise_for_status() + + # 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( { diff --git a/app/tts_cache.py b/app/tts_cache.py new file mode 100644 index 0000000..65845b9 --- /dev/null +++ b/app/tts_cache.py @@ -0,0 +1,83 @@ +import hashlib +from pathlib import Path +from typing import Optional + + +class TTSCache: + """In-disk audio caching mechanism for ElevenLabs TTS requests.""" + + def __init__(self, cache_dir: str = ".tts_cache"): + self.cache_dir = Path(cache_dir) + self.cache_dir.mkdir(parents=True, exist_ok=True) + + def _generate_key( + self, + text: str, + voice_id: str, + output_format: str, + model_id: str = "", + stability: float = 0.5, + similarity_boost: float = 0.75, + ) -> str: + """Generates a deterministic unique hash for a TTS request configuration.""" + raw_payload = ( + f"{text.strip()}|{voice_id}|{output_format}|" + f"{model_id}|{stability:.2f}|{similarity_boost:.2f}" + ) + return hashlib.sha256(raw_payload.encode("utf-8")).hexdigest() + + def get_extension(self, output_format: str) -> str: + """Determines file extension based on ElevenLabs output format.""" + if "pcm" in output_format.lower(): + return "pcm" + elif "wav" in output_format.lower(): + return "wav" + return "mp3" + + def get( + self, + text: str, + voice_id: str, + output_format: str, + model_id: str = "", + stability: float = 0.5, + similarity_boost: float = 0.75, + ) -> Optional[bytes]: + """Retrieves cached audio bytes if available, else returns None.""" + key = self._generate_key( + text, voice_id, output_format, model_id, stability, similarity_boost + ) + ext = self.get_extension(output_format) + file_path = self.cache_dir / f"{key}.{ext}" + + if file_path.exists(): + try: + with open(file_path, "rb") as f: + return f.read() + except Exception as e: + print(f"[TTSCache] Failed to read cached file {file_path}: {e}") + return None + return None + + def put( + self, + text: str, + voice_id: str, + output_format: str, + audio_data: bytes, + model_id: str = "", + stability: float = 0.5, + similarity_boost: float = 0.75, + ) -> None: + """Saves generated audio bytes into the disk cache.""" + key = self._generate_key( + text, voice_id, output_format, model_id, stability, similarity_boost + ) + ext = self.get_extension(output_format) + file_path = self.cache_dir / f"{key}.{ext}" + + try: + with open(file_path, "wb") as f: + f.write(audio_data) + except Exception as e: + print(f"[TTSCache] Failed to write to cache {file_path}: {e}") \ No newline at end of file