Spaces:
Sleeping
Sleeping
feat: implement OmniVoice zero-shot voice design and cloning endpoints with documentation architecture
8b5224b Download services/queue.py from ssamreshan/BizPiper: direct link, hf CLI and curl.
- Browser
- Download file 6.36 kB
-
https://huggingface.co/spaces/ssamreshan/BizPiper/resolve/main/services/queue.py
- Command line
-
hf download hf://spaces/ssamreshan/BizPiper/services/queue.py
-
curl -L -o queue.py https://huggingface.co/spaces/ssamreshan/BizPiper/resolve/main/services/queue.py
6.36 kB
| """ | |
| 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 ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| 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, | |
| } | |