Compare commits
7
Commits
54ea2f4564
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ec932581d | ||
|
|
86a79b971e | ||
|
|
59bffbed1a | ||
|
|
ebd0c12ef6 | ||
|
|
7d8bba7745 | ||
|
|
a910b206fe | ||
|
|
1bfee59c05 |
@@ -4,3 +4,6 @@ __pycache__/
|
||||
.env
|
||||
.DS_Store
|
||||
.playwright-mcp/
|
||||
# TTS Cache default directory
|
||||
.tts_cache/
|
||||
logs/
|
||||
@@ -0,0 +1,140 @@
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from logging.handlers import QueueHandler, QueueListener, RotatingFileHandler
|
||||
from queue import Queue
|
||||
from typing import Optional
|
||||
|
||||
_queue_listener: Optional[QueueListener] = None
|
||||
|
||||
MAX_LOG_FILE_SIZE = 10 * 1024 * 1024 # 10 MB
|
||||
BACKUP_COUNT = 5
|
||||
|
||||
|
||||
class WaterfallConsoleFormatter(logging.Formatter):
|
||||
"""Colorized console formatter for local terminal output."""
|
||||
|
||||
BLUE = "\x1b[34;20m"
|
||||
CYAN = "\x1b[36;20m"
|
||||
YELLOW = "\x1b[33;20m"
|
||||
RED = "\x1b[31;20m"
|
||||
BOLD_RED = "\x1b[31;1m"
|
||||
RESET = "\x1b[0m"
|
||||
|
||||
FORMAT = "%(asctime)s | %(levelname)-8s | %(name)s - %(message)s"
|
||||
|
||||
LEVEL_COLORS = {
|
||||
logging.DEBUG: "\x1b[38;20m",
|
||||
logging.INFO: CYAN,
|
||||
logging.WARNING: YELLOW,
|
||||
logging.ERROR: RED,
|
||||
logging.CRITICAL: BOLD_RED,
|
||||
}
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
color = self.BLUE if "WATERFALL" in record.getMessage() else self.LEVEL_COLORS.get(record.levelno, self.RESET)
|
||||
formatter = logging.Formatter(
|
||||
f"{color}{self.FORMAT}{self.RESET}",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
return formatter.format(record)
|
||||
|
||||
|
||||
class PlainFileFormatter(logging.Formatter):
|
||||
"""Strips ANSI color escape sequences prior to saving to disk."""
|
||||
|
||||
ANSI_ESCAPE = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
raw_message = super().format(record)
|
||||
return self.ANSI_ESCAPE.sub("", raw_message)
|
||||
|
||||
|
||||
def setup_logging(
|
||||
level: int = logging.INFO,
|
||||
json_format: bool = False,
|
||||
log_file_path: Optional[str] = "logs/waterfall.log",
|
||||
max_bytes: int = MAX_LOG_FILE_SIZE,
|
||||
backup_count: int = BACKUP_COUNT,
|
||||
) -> None:
|
||||
"""Configures unified, non-blocking queue logging for console and file handlers."""
|
||||
global _queue_listener
|
||||
|
||||
# Stop any previous listener if re-initialized
|
||||
if _queue_listener is not None:
|
||||
_queue_listener.stop()
|
||||
_queue_listener = None
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.setLevel(level)
|
||||
|
||||
# Clear existing handlers
|
||||
for handler in root_logger.handlers[:]:
|
||||
root_logger.removeHandler(handler)
|
||||
|
||||
handlers = []
|
||||
|
||||
# 1. Console Handler (JSON or Waterfall Colored Text)
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
if json_format:
|
||||
try:
|
||||
from pythonjsonlogger import jsonlogger
|
||||
console_handler.setFormatter(
|
||||
jsonlogger.JsonFormatter(
|
||||
"%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
timestamp=True,
|
||||
)
|
||||
)
|
||||
except ImportError:
|
||||
console_handler.setFormatter(
|
||||
logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
|
||||
)
|
||||
else:
|
||||
console_handler.setFormatter(WaterfallConsoleFormatter())
|
||||
handlers.append(console_handler)
|
||||
|
||||
# 2. Rotating File Handler (Non-blocking file write)
|
||||
if log_file_path:
|
||||
log_dir = os.path.dirname(log_file_path)
|
||||
if log_dir:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
file_handler = RotatingFileHandler(
|
||||
filename=log_file_path,
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding="utf-8",
|
||||
)
|
||||
file_handler.setFormatter(
|
||||
PlainFileFormatter(
|
||||
"%(asctime)s | %(levelname)-8s | %(name)s - %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
)
|
||||
handlers.append(file_handler)
|
||||
|
||||
# 3. Non-blocking Queue Setup
|
||||
log_queue: Queue = Queue(maxsize=-1)
|
||||
async_queue_handler = QueueHandler(log_queue)
|
||||
root_logger.addHandler(async_queue_handler)
|
||||
|
||||
# Dedicated thread drains log queue into stdout and file
|
||||
_queue_listener = QueueListener(
|
||||
log_queue,
|
||||
*handlers,
|
||||
respect_handler_level=True,
|
||||
)
|
||||
_queue_listener.start()
|
||||
|
||||
# Mute verbose libraries
|
||||
for noisy_lib in ("websockets", "httpx", "asyncio", "urllib3"):
|
||||
logging.getLogger(noisy_lib).setLevel(logging.WARNING)
|
||||
|
||||
|
||||
def shutdown_logging() -> None:
|
||||
"""Flushes queued logs and stops the listener thread on shutdown."""
|
||||
global _queue_listener
|
||||
if _queue_listener is not None:
|
||||
_queue_listener.stop()
|
||||
_queue_listener = None
|
||||
+144
-69
@@ -21,16 +21,37 @@ from fastapi.staticfiles import StaticFiles
|
||||
import httpx
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from app.tts_cache import CacheIOError, TTSCache
|
||||
from app.telemetry import time_span, trace_span
|
||||
from app.logging_config import setup_logging, shutdown_logging, MAX_LOG_FILE_SIZE, BACKUP_COUNT
|
||||
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")
|
||||
|
||||
logger = logging.getLogger("simple_call_center")
|
||||
|
||||
app = FastAPI(title="Simple Call Center")
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# Startup: Initialize logging once with all configuration settings
|
||||
is_json = os.getenv("LOG_FORMAT", "text").lower() == "json"
|
||||
setup_logging(
|
||||
level=logging.INFO,
|
||||
json_format=is_json,
|
||||
log_file_path="logs/waterfall.log",
|
||||
max_bytes=MAX_LOG_FILE_SIZE,
|
||||
backup_count=BACKUP_COUNT,
|
||||
)
|
||||
yield
|
||||
# Shutdown: Cleanly flush queue to file on exit
|
||||
shutdown_logging()
|
||||
|
||||
app = FastAPI(title="Simple Call Center", lifespan=lifespan)
|
||||
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
||||
|
||||
DEDUPLICATE_TRANSCRIPT_WINDOW_SECS = 4.0
|
||||
@@ -705,7 +726,8 @@ class VoiceSession:
|
||||
await self.respond_to_user(text)
|
||||
finally:
|
||||
self.mark_committed_transcript_done(text)
|
||||
|
||||
|
||||
@trace_span("VoiceSession.respond_to_user")
|
||||
async def respond_to_user(self, user_text: str) -> None:
|
||||
if openai_client is None:
|
||||
await self.send_json({"type": "error", "message": "OpenAI client is not configured."})
|
||||
@@ -746,15 +768,16 @@ class VoiceSession:
|
||||
if message.get("role") == "user"
|
||||
)
|
||||
retrieval_query = f"{retrieval_query} {user_text}".strip()
|
||||
kb_hits = (
|
||||
knowledge_base.search(
|
||||
retrieval_query,
|
||||
limit=settings.local_kb_max_results,
|
||||
min_score=settings.local_kb_min_score,
|
||||
async with time_span("knowledge_base_search"):
|
||||
kb_hits = (
|
||||
knowledge_base.search(
|
||||
retrieval_query,
|
||||
limit=settings.local_kb_max_results,
|
||||
min_score=settings.local_kb_min_score,
|
||||
)
|
||||
if settings.local_kb_enabled
|
||||
else []
|
||||
)
|
||||
if settings.local_kb_enabled
|
||||
else []
|
||||
)
|
||||
kb_context = format_knowledge_context(kb_hits)
|
||||
kb_context = prepare_model_context_text(kb_context)
|
||||
if kb_hits:
|
||||
@@ -790,21 +813,29 @@ class VoiceSession:
|
||||
}
|
||||
if settings.openai_reasoning_effort:
|
||||
request["reasoning"] = {"effort": settings.openai_reasoning_effort}
|
||||
|
||||
async with time_span("openai_llm_stream"):
|
||||
stream_start = time.perf_counter()
|
||||
first_token_received = False
|
||||
|
||||
stream = await openai_client.responses.create(**request)
|
||||
async for event in stream:
|
||||
event_type = getattr(event, "type", "")
|
||||
if event_type == "response.output_text.delta":
|
||||
delta = getattr(event, "delta", "")
|
||||
if delta:
|
||||
answer_parts.append(delta)
|
||||
elif event_type == "error":
|
||||
await self.send_json(
|
||||
{"type": "error", "message": getattr(event, "message", "OpenAI stream error")}
|
||||
)
|
||||
|
||||
answer = polish_assistant_answer("".join(answer_parts), user_text, self.conversation_language)
|
||||
answer = humanize_assistant_answer(answer, user_text, self.conversation_language)
|
||||
stream = await openai_client.responses.create(**request)
|
||||
async for event in stream:
|
||||
event_type = getattr(event, "type", "")
|
||||
if event_type == "response.output_text.delta":
|
||||
if not first_token_received:
|
||||
ttft_ms = (time.perf_counter() - stream_start) * 1000
|
||||
logger.info("WATERFALL | │ ├── OpenAI TTFT: %.2fms", ttft_ms)
|
||||
first_token_received = True
|
||||
delta = getattr(event, "delta", "")
|
||||
if delta:
|
||||
answer_parts.append(delta)
|
||||
elif event_type == "error":
|
||||
await self.send_json(
|
||||
{"type": "error", "message": getattr(event, "message", "OpenAI stream error")}
|
||||
)
|
||||
async with time_span("post_process_answer"):
|
||||
answer = polish_assistant_answer("".join(answer_parts), user_text, self.conversation_language)
|
||||
answer = humanize_assistant_answer(answer, user_text, self.conversation_language)
|
||||
await self.emit_assistant_answer(user_text, answer, tts_queue, tts_language)
|
||||
except Exception as exc:
|
||||
await self.send_json({"type": "error", "message": f"OpenAI error: {exc}"})
|
||||
@@ -838,58 +869,102 @@ class VoiceSession:
|
||||
if answer and not settings.streaming_tts_enabled:
|
||||
await self.synthesize_tts_http(answer, tts_language)
|
||||
|
||||
@trace_span("ElevenLabs.synthesize_tts_http")
|
||||
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)
|
||||
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}
|
||||
payload: dict[str, Any] = {
|
||||
"text": prepare_tts_text(text, tts_language),
|
||||
prepared_text = prepare_tts_text(text, tts_language)
|
||||
output_format = settings.elevenlabs_tts_output_format
|
||||
|
||||
cache_params = {
|
||||
"text": prepared_text,
|
||||
"voice_id": voice_id,
|
||||
"output_format": output_format,
|
||||
"model_id": settings.elevenlabs_tts_model,
|
||||
"voice_settings": {
|
||||
"stability": settings.elevenlabs_tts_stability,
|
||||
"similarity_boost": settings.elevenlabs_tts_similarity_boost,
|
||||
"use_speaker_boost": False,
|
||||
"speed": settings.elevenlabs_tts_speed,
|
||||
},
|
||||
"stability": settings.elevenlabs_tts_stability,
|
||||
"similarity_boost": settings.elevenlabs_tts_similarity_boost,
|
||||
}
|
||||
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,
|
||||
key = tts_cache._generate_key(**cache_params)
|
||||
|
||||
# Clean context manager handles acquisition, locking, and resource release automatically
|
||||
async with tts_cache.lock(key):
|
||||
# Check cache
|
||||
try:
|
||||
async with time_span("tts_cache_check"):
|
||||
cached_audio = await tts_cache.get(**cache_params)
|
||||
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
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to read TTS cache: %s", exc)
|
||||
|
||||
# Miss (Executed only once across concurrent tasks for this key)
|
||||
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,
|
||||
"model_id": settings.elevenlabs_tts_model,
|
||||
"voice_settings": {
|
||||
"stability": settings.elevenlabs_tts_stability,
|
||||
"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, time_span("elevenlabs_api_post"):
|
||||
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()
|
||||
|
||||
# Isolated write: I/O disk failures will not disrupt returning audio to user
|
||||
try:
|
||||
async with time_span("tts_cache_write"):
|
||||
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(
|
||||
{
|
||||
"type": "tts_audio",
|
||||
"audio": base64.b64encode(response.content).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()
|
||||
|
||||
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}")
|
||||
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(
|
||||
self,
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextvars
|
||||
import functools
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any, Callable, TypeVar
|
||||
|
||||
logger = logging.getLogger("simple_call_center.telemetry")
|
||||
|
||||
_current_trace_id: contextvars.ContextVar[str | None] = contextvars.ContextVar("trace_id", default=None)
|
||||
_current_parent_span: contextvars.ContextVar[str | None] = contextvars.ContextVar("parent_span", default=None)
|
||||
_current_depth: contextvars.ContextVar[int] = contextvars.ContextVar("depth", default=0)
|
||||
|
||||
F = TypeVar("F", bound=Callable[..., Any])
|
||||
|
||||
|
||||
def trace_span(name: str | None = None):
|
||||
"""Decorator for tracing sync/async functions in a waterfall hierarchy."""
|
||||
def decorator(func: F) -> F:
|
||||
span_name = name or func.__qualname__
|
||||
|
||||
@functools.wraps(func)
|
||||
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
async with time_span(span_name):
|
||||
return await func(*args, **kwargs)
|
||||
|
||||
@functools.wraps(func)
|
||||
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
return _run_sync_span(span_name, func, *args, **kwargs)
|
||||
|
||||
return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper # type: ignore
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def time_span(span_name: str, **attributes: Any):
|
||||
"""Context manager for tracing code blocks."""
|
||||
trace_id = _current_trace_id.get()
|
||||
is_root = trace_id is None
|
||||
|
||||
if is_root:
|
||||
trace_id = f"tr-{uuid.uuid4().hex[:8]}"
|
||||
_current_trace_id.set(trace_id)
|
||||
|
||||
parent_span = _current_parent_span.get() or "ROOT"
|
||||
span_id = f"sp-{uuid.uuid4().hex[:6]}"
|
||||
depth = _current_depth.get()
|
||||
|
||||
t_parent = _current_parent_span.set(span_id)
|
||||
t_depth = _current_depth.set(depth + 1)
|
||||
|
||||
indent = " │ " * depth + " ├─ " if depth > 0 else "┌─ "
|
||||
attrs_str = f" | {attributes}" if attributes else ""
|
||||
|
||||
logger.info(
|
||||
"WATERFALL | %s %s [START] [trace_id=%s span_id=%s parent=%s]%s",
|
||||
indent,
|
||||
span_name,
|
||||
trace_id,
|
||||
span_id,
|
||||
parent_span,
|
||||
attrs_str,
|
||||
extra={
|
||||
"trace_id": trace_id,
|
||||
"span_id": span_id,
|
||||
"parent_span": parent_span,
|
||||
"span_name": span_name,
|
||||
"event": "start",
|
||||
},
|
||||
)
|
||||
|
||||
start_time = time.perf_counter()
|
||||
try:
|
||||
yield span_id
|
||||
finally:
|
||||
duration_ms = (time.perf_counter() - start_time) * 1000
|
||||
end_indent = " │ " * depth + " └─ " if depth > 0 else "└─ "
|
||||
|
||||
logger.info(
|
||||
"WATERFALL | %s %s [END SUCCESS] duration=%.2fms [trace_id=%s span_id=%s parent=%s]",
|
||||
end_indent,
|
||||
span_name,
|
||||
duration_ms,
|
||||
trace_id,
|
||||
span_id,
|
||||
parent_span,
|
||||
extra={
|
||||
"trace_id": trace_id,
|
||||
"span_id": span_id,
|
||||
"parent_span": parent_span,
|
||||
"span_name": span_name,
|
||||
"duration_ms": round(duration_ms, 2),
|
||||
"event": "end",
|
||||
},
|
||||
)
|
||||
|
||||
_current_parent_span.reset(t_parent)
|
||||
_current_depth.reset(t_depth)
|
||||
if is_root:
|
||||
_current_trace_id.set(None)
|
||||
|
||||
|
||||
def _run_sync_span(span_name: str, func: Callable, *args: Any, **kwargs: Any) -> Any:
|
||||
trace_id = _current_trace_id.get()
|
||||
is_root = trace_id is None
|
||||
|
||||
if is_root:
|
||||
trace_id = f"tr-{uuid.uuid4().hex[:8]}"
|
||||
_current_trace_id.set(trace_id)
|
||||
|
||||
parent_span = _current_parent_span.get() or "ROOT"
|
||||
span_id = f"sp-{uuid.uuid4().hex[:6]}"
|
||||
depth = _current_depth.get()
|
||||
|
||||
t_parent = _current_parent_span.set(span_id)
|
||||
t_depth = _current_depth.set(depth + 1)
|
||||
|
||||
indent = " │ " * depth + " ├─ " if depth > 0 else "┌─ "
|
||||
logger.info(
|
||||
"WATERFALL | %s %s [START] [trace_id=%s span_id=%s parent=%s]",
|
||||
indent,
|
||||
span_name,
|
||||
trace_id,
|
||||
span_id,
|
||||
parent_span,
|
||||
)
|
||||
|
||||
start_time = time.perf_counter()
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
finally:
|
||||
duration_ms = (time.perf_counter() - start_time) * 1000
|
||||
end_indent = " │ " * depth + " └─ " if depth > 0 else "└─ "
|
||||
logger.info(
|
||||
"WATERFALL | %s %s [END SUCCESS] duration=%.2fms [trace_id=%s span_id=%s parent=%s]",
|
||||
end_indent,
|
||||
span_name,
|
||||
duration_ms,
|
||||
trace_id,
|
||||
span_id,
|
||||
parent_span,
|
||||
)
|
||||
_current_parent_span.reset(t_parent)
|
||||
_current_depth.reset(t_depth)
|
||||
if is_root:
|
||||
_current_trace_id.set(None)
|
||||
@@ -0,0 +1,220 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import tempfile
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
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:
|
||||
"""Simple in-disk audio cache with atomic writes, LRU eviction, and request locks."""
|
||||
|
||||
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.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(
|
||||
self,
|
||||
text: str,
|
||||
voice_id: str,
|
||||
output_format: str,
|
||||
model_id: str = "",
|
||||
stability: float = 0.5,
|
||||
similarity_boost: float = 0.75,
|
||||
) -> str:
|
||||
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:
|
||||
fmt = output_format.lower()
|
||||
if "pcm" in fmt:
|
||||
return "pcm"
|
||||
if "wav" in fmt:
|
||||
return "wav"
|
||||
return "mp3"
|
||||
|
||||
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 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(
|
||||
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."""
|
||||
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:
|
||||
exists = await asyncio.to_thread(file_path.exists)
|
||||
if exists:
|
||||
# Update timestamp for LRU tracking
|
||||
await asyncio.to_thread(file_path.touch, exist_ok=True)
|
||||
data = await asyncio.to_thread(file_path.read_bytes)
|
||||
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
|
||||
|
||||
async 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 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(
|
||||
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:
|
||||
await asyncio.to_thread(self.cache_dir.mkdir, parents=True, exist_ok=True)
|
||||
|
||||
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
|
||||
|
||||
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)
|
||||
@@ -2,5 +2,6 @@ fastapi>=0.115.0
|
||||
uvicorn[standard]>=0.30.0
|
||||
openai>=1.88.0
|
||||
python-dotenv>=1.0.1
|
||||
python-json-logger>=2.0.7
|
||||
httpx>=0.28.0
|
||||
websockets>=12.0,<16.0
|
||||
|
||||
Reference in New Issue
Block a user