30 lines
1002 B
Python
30 lines
1002 B
Python
import threading
|
|
from contextlib import contextmanager
|
|
|
|
from app.config.settings import settings
|
|
from app.exceptions.service_busy_exception import ServiceBusyException
|
|
|
|
|
|
class InferenceLimiter:
|
|
"""Ограничивает число одновременных прогонов моделей (синхронные эндпоинты)."""
|
|
|
|
def __init__(self, name: str, max_concurrency: int):
|
|
self.name = name
|
|
self._semaphore = threading.BoundedSemaphore(max(1, max_concurrency))
|
|
|
|
@contextmanager
|
|
def slot(self, timeout: float | None = None):
|
|
timeout = settings.INFERENCE_QUEUE_TIMEOUT if timeout is None else timeout
|
|
if not self._semaphore.acquire(timeout=timeout):
|
|
raise ServiceBusyException(
|
|
f"{self.name} moderation is busy, retry later"
|
|
)
|
|
try:
|
|
yield
|
|
finally:
|
|
self._semaphore.release()
|
|
|
|
|
|
image_limiter = InferenceLimiter("Image", settings.IMAGE_MAX_CONCURRENCY)
|
|
text_limiter = InferenceLimiter("Text", settings.TEXT_MAX_CONCURRENCY)
|