Spaces:
Configuration error

File size: 1,088 Bytes
f1ba785
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""@module numeric-inference/admission — cap in-flight recognize calls. Probes stay open."""

from __future__ import annotations

import asyncio
import os

from fastapi.responses import JSONResponse

RECOGNIZE_PATHS = frozenset({
    "/v1/recognize/lines",
    "/v1/recognize/numeric",
    "/v1/recognize/numeric:batch",
})


def recognize_semaphore() -> asyncio.Semaphore:
    raw = os.getenv("AXIS_HTTP_CONCURRENCY", "4").strip()
    try:
        count = max(1, int(raw))
    except ValueError:
        count = 4
    return asyncio.Semaphore(count)


async def admit(request, call_next, slots: asyncio.Semaphore):
    if request.url.path not in RECOGNIZE_PATHS:
        return await call_next(request)
    try:
        await asyncio.wait_for(slots.acquire(), timeout=0.05)
    except TimeoutError:
        return JSONResponse(
            status_code=503,
            content={"detail": "inference_busy"},
            headers={"retry-after": "1"},
        )
    try:
        return await call_next(request)
    finally:
        slots.release()