/** * Server-side detection fallback. * * When a device cannot load / run the in-browser ONNX model (old Android, * no WebGPU, low memory, blocked WASM, etc.) we POST the original photo to the * FastAPI `/detect` endpoint which runs the same model on the server CPU. */ import type { Detection } from './types' import { reassignDetectionIds } from './postprocess' interface ServerDetectResponse { detections: Array<{ xmin: number; ymin: number; xmax: number; ymax: number; confidence: number }> count: number width: number height: number ms: number model: string mode: string backend: string } let serverBackend = 'server' export function getServerBackend(): string { return serverBackend } export function isServerTimeoutError(err: unknown): boolean { const msg = err instanceof Error ? err.message : String(err) return /timed out/i.test(msg) || msg.includes('(504)') } /** * Probe whether the server-side detection fallback is reachable and ready. * Returns false on any network error (e.g. installed PWA running offline). */ export async function isServerDetectAvailable(timeoutMs = 8000): Promise { try { const controller = new AbortController() const timer = setTimeout(() => controller.abort(), timeoutMs) const res = await fetch('/health', { signal: controller.signal, cache: 'no-store' }) clearTimeout(timer) if (!res.ok) return false const data = (await res.json()) as { server_detect?: boolean } return Boolean(data.server_detect) } catch { return false } } /** Health probe with retries — HF cold starts can miss a single 4s check. */ export async function probeServerDetect(options?: { timeoutMs?: number retries?: number delayMs?: number }): Promise { const retries = options?.retries ?? 3 const timeoutMs = options?.timeoutMs ?? 8000 const delayMs = options?.delayMs ?? 600 for (let i = 0; i < retries; i++) { if (await isServerDetectAvailable(timeoutMs)) return true if (i < retries - 1) { await new Promise((r) => setTimeout(r, delayMs * (i + 1))) } } return false } const SERVER_DETECT_RETRIES = 2 async function serverDetectOnce( file: Blob, options?: { useTiling?: boolean filterOutliers?: boolean onProgress?: (msg: string) => void }, ): Promise { options?.onProgress?.('Uploading to server...') const form = new FormData() form.append('file', file, 'photo.jpg') form.append('tiling', String(options?.useTiling ?? false)) form.append('auto_tile', String(options?.useTiling ? false : true)) form.append('outliers', String(options?.filterOutliers ?? false)) options?.onProgress?.('Counting on server...') const res = await fetch('/detect', { method: 'POST', body: form }) if (!res.ok) { let detail = `Server detection failed (${res.status})` try { const err = (await res.json()) as { detail?: string | { message?: string } } if (typeof err.detail === 'string') { detail = err.detail } else if (err.detail && typeof err.detail === 'object' && err.detail.message) { detail = err.detail.message } } catch { /* ignore parse error */ } throw new Error(detail) } const data = (await res.json()) as ServerDetectResponse serverBackend = data.backend ?? 'server' options?.onProgress?.(`Detected ${data.count} pipes (${data.ms}ms, ${serverBackend})`) return reassignDetectionIds( data.detections.map((d) => ({ xmin: d.xmin, ymin: d.ymin, xmax: d.xmax, ymax: d.ymax, confidence: d.confidence, id: '', groupId: 0, })), 'srv', ) } export async function serverDetect( file: Blob, options?: { useTiling?: boolean filterOutliers?: boolean onProgress?: (msg: string) => void retries?: number }, ): Promise { const retries = options?.retries ?? SERVER_DETECT_RETRIES let lastErr: unknown for (let attempt = 0; attempt <= retries; attempt++) { try { return await serverDetectOnce(file, options) } catch (err) { lastErr = err if (attempt < retries) { options?.onProgress?.('Retrying server…') await new Promise((r) => setTimeout(r, 800 * (attempt + 1))) } } } throw lastErr instanceof Error ? lastErr : new Error(String(lastErr)) }