Files
voice-call-center-ai/app/tts_cache.py
T
2026-09-23 11:44:07 +05:00

83 lines
2.6 KiB
Python

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}")