Spaces:
Sleeping
Sleeping
Download app/services/tool_gate.py from Rthur2003/crowncode-backend: direct link, hf CLI and curl.
- Browser
- Download file 2.21 kB
-
https://huggingface.co/spaces/Rthur2003/crowncode-backend/resolve/main/app/services/tool_gate.py
- Command line
-
hf download hf://spaces/Rthur2003/crowncode-backend/app/services/tool_gate.py
-
curl -L -o tool_gate.py https://huggingface.co/spaces/Rthur2003/crowncode-backend/resolve/main/app/services/tool_gate.py
2.21 kB
| """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 | |
| 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) | |