Spaces:
Sleeping
Sleeping
File size: 6,364 Bytes
79a5814 8b5224b 79a5814 8b5224b 79a5814 8b5224b 79a5814 8b5224b 79a5814 8b5224b 79a5814 8b5224b 79a5814 8b5224b 79a5814 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | """
services/queue.py
βββββββββββββββββ
Async inference queue that serialises all ONNX synthesis calls onto a
single background worker thread, preventing:
- Concurrent ONNX calls that would cause memory spikes
- Blocking the FastAPI event loop during CPU-heavy inference
Architecture:
βββββββββββββββββββββββββββββββββββ
β FastAPI event loop (async) β
β POST /synthesize β
β ββ enqueue_synthesis() β β puts a Future onto the queue
β ββ await future β β suspends without blocking the loop
ββββββββββββββββ¬βββββββββββββββββββ
β asyncio.Queue (bounded)
ββββββββββββββββΌβββββββββββββββββββ
β ThreadPoolExecutor (1 thread) β
β _worker_loop() β β pulls jobs, runs ONNX inference
β ββ core.tts_engine.synthesize()
βββββββββββββββββββββββββββββββββββ
The queue is bounded (settings.queue_max_size). If full, new requests
immediately receive a 503 Service Unavailable response β preventing
runaway memory usage under load spikes.
"""
import asyncio
import logging
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from typing import Any, Callable
from core.config import get_settings
from core.tts_engine import synthesize as _synthesize_sync
logger = logging.getLogger(__name__)
# ββ Job dataclass ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@dataclass
class SynthesisJob:
func: Callable
args: tuple
kwargs: dict
future: asyncio.Future = field(default_factory=asyncio.Future)
# ββ Queue worker βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_queue: asyncio.Queue | None = None
_executor: ThreadPoolExecutor | None = None
_worker_task: asyncio.Task | None = None
async def _worker_loop() -> None:
"""
Continuously pulls SynthesisJobs from the queue and executes them
on the thread-pool executor (one thread β one ONNX job at a time).
"""
loop = asyncio.get_running_loop()
logger.info("Synthesis queue worker started.")
while True:
try:
job: SynthesisJob = await _queue.get()
if job.future.cancelled():
_queue.task_done()
continue
try:
wav_bytes: bytes = await loop.run_in_executor(
_executor,
lambda: job.func(*job.args, **job.kwargs)
)
if not job.future.cancelled():
job.future.set_result(wav_bytes)
except Exception as exc:
if not job.future.cancelled():
job.future.set_exception(exc)
finally:
_queue.task_done()
except asyncio.CancelledError:
logger.info("Synthesis queue worker shutting down.")
break
except Exception:
logger.exception("Unexpected error in queue worker loop β continuing.")
# ββ Public lifecycle API βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def start_queue() -> None:
"""
Initialise the queue and launch the background worker.
Must be called once inside a running asyncio event loop
(e.g. from a FastAPI lifespan startup handler).
"""
global _queue, _executor, _worker_task
settings = get_settings()
_queue = asyncio.Queue(maxsize=settings.queue_max_size)
# Single-threaded executor β ONNX inference is not thread-safe on some models
_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="onnx_worker")
_worker_task = asyncio.create_task(_worker_loop())
logger.info(
"Synthesis queue initialised (max_size=%d, timeout=%ds).",
settings.queue_max_size,
settings.queue_timeout_seconds,
)
async def stop_queue() -> None:
"""
Gracefully shut down the queue worker.
Called from the FastAPI lifespan shutdown handler.
"""
global _worker_task, _executor
if _worker_task:
_worker_task.cancel()
try:
await _worker_task
except asyncio.CancelledError:
pass
if _executor:
_executor.shutdown(wait=False)
logger.info("Synthesis queue stopped.")
async def enqueue_job(func: Callable, *args, **kwargs) -> bytes:
"""
Submit a generic synthesis job to the queue and await its result.
Returns: WAV audio bytes.
Raises: asyncio.QueueFull or asyncio.TimeoutError
"""
if _queue is None:
raise RuntimeError("Synthesis queue has not been started.")
settings = get_settings()
loop = asyncio.get_running_loop()
future: asyncio.Future[bytes] = loop.create_future()
job = SynthesisJob(
func=func,
args=args,
kwargs=kwargs,
future=future,
)
try:
_queue.put_nowait(job)
except asyncio.QueueFull as exc:
raise asyncio.QueueFull(
"Synthesis queue is at capacity. Please retry shortly."
) from exc
return await asyncio.wait_for(future, timeout=settings.queue_timeout_seconds)
async def enqueue_synthesis(
template: str,
variables: dict[str, str],
voice_key: str,
speed: float,
) -> bytes:
"""Legacy helper for the main synthesize endpoint."""
return await enqueue_job(_synthesize_sync, template, variables, voice_key, speed)
def queue_stats() -> dict[str, Any]:
"""Return diagnostic statistics for the /health endpoint."""
if _queue is None:
return {"status": "not_started"}
return {
"status": "running",
"queue_size": _queue.qsize(),
"queue_max_size": _queue.maxsize,
}
|