Spaces:
Sleeping
Sleeping
File size: 2,208 Bytes
a427438 | 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 | """Keeps the Creator Studio and ML Toolkit audio work off the event loop.
Remixing, mixing, converting and tagging audio are CPU-bound librosa calls. Run
inline in an async handler they freeze the whole server (health checks, AURIS
polling, other downloads) until they finish. They go to a worker thread
instead, and at most TOOLS_CPU_SLOTS of them run at once so two visitors'
jobs don't starve each other and the AURIS analysis on the same CPU.
"""
from __future__ import annotations
import asyncio
import os
from contextlib import asynccontextmanager
from typing import Any, AsyncIterator, Callable, Optional, TypeVar
from fastapi import HTTPException, status
from starlette.concurrency import run_in_threadpool
T = TypeVar("T")
TOOL_SLOTS = max(1, int(os.getenv("TOOLS_CPU_SLOTS", "1")))
# Jobs allowed to wait for a slot; past that the visitor is told to come back.
MAX_WAITING = max(1, int(os.getenv("TOOLS_MAX_WAITING", "6")))
_semaphore: Optional[asyncio.Semaphore] = None
_semaphore_loop: Optional[asyncio.AbstractEventLoop] = None
_waiting = 0
def waiting() -> int:
return _waiting
@asynccontextmanager
async def tool_slot() -> AsyncIterator[None]:
global _semaphore, _semaphore_loop, _waiting
loop = asyncio.get_running_loop()
if _semaphore is None or _semaphore_loop is not loop:
# One per event loop: a semaphore must not be shared across loops (tests start several).
_semaphore, _semaphore_loop, _waiting = asyncio.Semaphore(TOOL_SLOTS), loop, 0
if _waiting >= MAX_WAITING:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail={"code": "server_busy", "message": "Too many audio jobs are waiting. Try again in a minute."},
headers={"Retry-After": "30"},
)
_waiting += 1
try:
await _semaphore.acquire()
finally:
_waiting -= 1
try:
yield
finally:
_semaphore.release()
async def run_blocking(fn: Callable[..., T], *args: Any, **kwargs: Any) -> T:
"""Run a CPU-bound function in a worker thread, waiting for a free slot first."""
async with tool_slot():
return await run_in_threadpool(fn, *args, **kwargs)
|