Spaces:
Runtime error
Runtime error
Download frontend/src/lib/serverDetect.ts from npisb/pipecountapp-dev: direct link, hf CLI and curl.
- Browser
- Download file 3.89 kB
-
https://huggingface.co/spaces/npisb/pipecountapp-dev/resolve/a34f5755f8fee2e18fc00a54ec4d76811bf2def0/frontend/src/lib/serverDetect.ts
- Command line
-
hf download hf://spaces/npisb/pipecountapp-dev@a34f5755f8fee2e18fc00a54ec4d76811bf2def0/frontend/src/lib/serverDetect.ts
-
curl -L -o serverDetect.ts https://huggingface.co/spaces/npisb/pipecountapp-dev/resolve/a34f5755f8fee2e18fc00a54ec4d76811bf2def0/frontend/src/lib/serverDetect.ts
3.89 kB
| /** | |
| * 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' | |
| 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 | |
| } | |
| /** | |
| * 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<boolean> { | |
| 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<boolean> { | |
| 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<Detection[]> { | |
| 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 } | |
| if (err.detail) detail = err.detail | |
| } 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 data.detections.map((d, idx) => ({ | |
| xmin: d.xmin, | |
| ymin: d.ymin, | |
| xmax: d.xmax, | |
| ymax: d.ymax, | |
| confidence: d.confidence, | |
| id: `srv-${idx}`, | |
| groupId: 0, | |
| })) | |
| } | |
| export async function serverDetect( | |
| file: Blob, | |
| options?: { | |
| useTiling?: boolean | |
| filterOutliers?: boolean | |
| onProgress?: (msg: string) => void | |
| retries?: number | |
| }, | |
| ): Promise<Detection[]> { | |
| 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)) | |
| } | |