drpig-web / app /classify.py
CJR61's picture
D-68 AI 改寫追問、D-69 附段相關、papi_cc 逾時硬上限 (prompt_source 07e4e3ce)
1c80894 verified
Raw History Blame Contribute Delete
3.67 kB
"""papi_cc client (docs/11 §8.4d, docs/01 NFR-05).
The whole call must finish inside the App's 60 s request timeout (app config `apiTimeout`): otherwise the App gives
up first, judges the photo on the phone and the cloud answer is lost (2026-11-25 09:12, 「無法判讀」). So every attempt
shares one deadline (`PAPI_BUDGET_S`, default 50 s). A failed attempt that looks like a cold / restarting Space
(timeout, connection error, 5xx) first pings papi_cc's root to wake it, then retries with what is left of the budget.
4xx is not retried (a bad key or a bad image will not get better).
"""
import asyncio
import os
import time
import httpx
PAPI_URL = os.getenv("PAPI_URL", "https://cjr61-papi-cc.hf.space/predict/")
PAPI_KEY = os.getenv("PAPI_CC_KEY", "")
PAPI_BUDGET_S = float(os.getenv("PAPI_BUDGET_S", "50")) # < App apiTimeout 60 s
PER_TRY_S = 25.0 # a warm papi_cc answers in ~1-3 s; 25 s leaves room for a slow first call
WARM_S = 20.0 # cap on the wake-up ping
MIN_TRY_S = 3.0 # not worth starting an attempt with less than this left
MAX_RETRY = 3 # total attempts
BACKOFF = [1, 2] # wait seconds before 2nd and 3rd attempt
def _root(url: str) -> str:
i = url.find("/", url.find("//") + 2)
return url if i < 0 else url[: i + 1]
def _retryable(e: Exception) -> bool:
if isinstance(e, httpx.HTTPStatusError):
return e.response.status_code >= 500
return isinstance(e, (httpx.TransportError, asyncio.TimeoutError))
async def _warm(client: httpx.AsyncClient, timeout: float) -> None:
try:
await client.get(_root(PAPI_URL), timeout=timeout)
except Exception:
pass
async def _attempts(client: httpx.AsyncClient, file_bytes: bytes, filename: str, deadline: float) -> dict:
headers = {"X-API-Key": PAPI_KEY}
last_exc: Exception | None = None
for attempt in range(MAX_RETRY):
if attempt > 0:
wait = BACKOFF[attempt - 1]
if deadline - time.monotonic() - wait < MIN_TRY_S: # not enough budget left for another try
break
await asyncio.sleep(wait)
left = deadline - time.monotonic()
if left > MIN_TRY_S + 1:
await _warm(client, min(WARM_S, left - MIN_TRY_S))
left = deadline - time.monotonic()
if left < MIN_TRY_S:
break
per_try = min(PER_TRY_S, left)
try:
async with asyncio.timeout(per_try): # wall clock: httpx timeouts are per phase / idle
resp = await client.post(PAPI_URL, headers=headers, timeout=per_try,
files={"file": (filename, file_bytes, "image/jpeg")})
resp.raise_for_status()
return resp.json()
except TimeoutError:
last_exc = TimeoutError(f"papi_cc timeout after {per_try:.0f}s")
except Exception as e:
last_exc = e
if not _retryable(e):
break
raise last_exc or TimeoutError(f"papi_cc timeout after {PAPI_BUDGET_S:.0f}s")
async def classify_image(file_bytes: bytes, filename: str) -> dict:
"""Hard wall-clock cap of PAPI_BUDGET_S over every attempt, wake-up ping and backoff sleep."""
deadline = time.monotonic() + PAPI_BUDGET_S
async with httpx.AsyncClient() as client:
try:
async with asyncio.timeout(PAPI_BUDGET_S):
return await _attempts(client, file_bytes, filename, deadline)
except TimeoutError as e:
if str(e):
raise
raise TimeoutError(f"papi_cc timeout after {PAPI_BUDGET_S:.0f}s") from None