File size: 3,886 Bytes
06bdaca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0758854
06bdaca
 
 
0758854
06bdaca
 
 
 
 
 
 
 
 
0758854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06bdaca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0758854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/**
 * 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))
}