File size: 13,183 Bytes
0e0cc3e
2b21a73
2eba938
 
 
 
 
 
0e0cc3e
c9976d7
0e0cc3e
b505c60
0e0cc3e
 
 
d600757
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d64e218
 
 
 
 
 
 
 
 
 
 
 
d600757
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e0cc3e
 
d64e218
 
 
0e0cc3e
d600757
 
 
 
 
0e0cc3e
d600757
 
 
 
 
 
 
0e0cc3e
d600757
0e0cc3e
d600757
0e0cc3e
d600757
0e0cc3e
 
 
d64e218
 
 
 
 
 
0e0cc3e
 
d600757
 
 
 
0e0cc3e
 
d600757
 
 
 
 
0e0cc3e
 
 
 
 
d600757
 
 
 
 
0e0cc3e
 
 
 
 
 
 
 
 
d600757
 
 
0e0cc3e
d600757
 
 
0e0cc3e
 
2eba938
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190dbf0
2eba938
 
 
 
 
 
 
 
 
0e0cc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190dbf0
0e0cc3e
 
 
 
 
 
 
 
 
 
2eba938
 
 
 
 
 
 
b505c60
2eba938
0e0cc3e
 
2eba938
 
 
d600757
 
 
 
0e0cc3e
 
 
2eba938
 
 
 
 
 
 
 
 
0e0cc3e
2eba938
 
190dbf0
 
 
b505c60
 
190dbf0
 
c9976d7
190dbf0
 
 
 
0e0cc3e
 
0fdcb52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e0cc3e
 
 
 
2eba938
 
 
 
 
b505c60
2eba938
0e0cc3e
 
 
 
2eba938
2b21a73
2eba938
 
0e0cc3e
 
2eba938
 
 
 
 
0fdcb52
 
 
2eba938
 
 
 
 
 
0fdcb52
 
 
 
 
 
 
 
2eba938
0fdcb52
 
2eba938
0fdcb52
2eba938
 
 
 
0fdcb52
 
 
 
2eba938
0fdcb52
 
 
 
 
 
 
0e0cc3e
c9976d7
 
 
b505c60
 
c9976d7
 
 
0e0cc3e
 
 
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import * as ort from 'onnxruntime-web'
import { CONFIDENCE_THRESHOLD, IOU_THRESHOLD, MAX_DETECTIONS, MODEL_640_URL, MODEL_URL, TILE_OVERLAP } from './constants'
import {
  enhanceImageElement,
  shouldAutoTile,
  suggestTileGrid,
  type EnhanceOptions,
} from './imageEnhance'
import { selectModelForImage } from './modelSelect'
import { nonMaxSuppression, postProcessPipeline, reassignDetectionIds } from './postprocess'
import { canvasToTensor, letterboxCanvas, mapBoxToOriginal } from './preprocess'
import type { Detection, LetterboxMeta, PostProcessReport } from './types'

ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.26.0/dist/'

// ---------------------------------------------------------------------------
// Backend capability detection (important for low-end Android devices)
// ---------------------------------------------------------------------------

// Multi-threaded WASM needs SharedArrayBuffer, which is only available when the
// page is cross-origin isolated (COOP/COEP). Static hosts (e.g. HF Spaces) don't
// set those headers, so we must run single-threaded — otherwise ORT may try to
// spawn workers and crash on weak devices.
function resolveThreadCount(): number {
  const hasSAB = typeof SharedArrayBuffer !== 'undefined'
  const isolated = typeof globalThis !== 'undefined'
    && Boolean((globalThis as { crossOriginIsolated?: boolean }).crossOriginIsolated)
  if (!hasSAB || !isolated) return 1
  const cores = typeof navigator !== 'undefined' ? navigator.hardwareConcurrency || 2 : 2
  return Math.max(1, Math.min(4, cores))
}

ort.env.wasm.numThreads = resolveThreadCount()
ort.env.wasm.simd = true

// Device memory in GB (Chrome/Android only; capped at 8, undefined elsewhere).
export function getDeviceMemoryGB(): number | undefined {
  const m = (navigator as unknown as { deviceMemory?: number }).deviceMemory
  return typeof m === 'number' && m > 0 ? m : undefined
}

// Heuristic for memory-constrained devices (typical low-price Android phones).
export function isLowMemoryDevice(): boolean {
  const m = getDeviceMemoryGB()
  return m !== undefined && m <= 4
}

// WebGPU often *creates* a session on cheap Android GPUs but then throws at
// run() time. We pre-check for a usable adapter and additionally warm up each
// session so a broken backend is rejected before we depend on it.
let webgpuChecked = false
let webgpuOk = false
async function isWebgpuUsable(): Promise<boolean> {
  if (webgpuChecked) return webgpuOk
  webgpuChecked = true
  try {
    const gpu = (navigator as unknown as { gpu?: { requestAdapter(): Promise<unknown> } }).gpu
    if (!gpu) { webgpuOk = false; return false }
    const adapter = await gpu.requestAdapter()
    webgpuOk = Boolean(adapter)
  } catch {
    webgpuOk = false
  }
  return webgpuOk
}

// Map each model to the input size used to warm it up.
const MODEL_WARMUP_SIZE: Record<string, number> = {
  [MODEL_URL]: 1024,
  [MODEL_640_URL]: 640,
}

let sessionCache = new Map<string, Promise<ort.InferenceSession>>()
let activeBackend = 'loading'
// Once a backend has proven it can actually run inference we don't warm up
// subsequent (larger) models — a 1024 warmup is heavy and risks OOM on phones.
let backendValidated = false

async function warmUp(session: ort.InferenceSession, size: number): Promise<void> {
  const dummy = new ort.Tensor('float32', new Float32Array(3 * size * size), [1, 3, size, size])
  await session.run({ images: dummy })
}

async function createSession(modelUrl: string): Promise<ort.InferenceSession> {
  const warmSize = MODEL_WARMUP_SIZE[modelUrl] ?? 640

  const backends: Array<{ name: string; providers: ort.InferenceSession.SessionOptions['executionProviders'] }> = []
  if (await isWebgpuUsable()) {
    backends.push({ name: 'webgpu', providers: ['webgpu', 'wasm'] })
  }
  backends.push({ name: 'wasm', providers: ['wasm'] })

  let lastError: unknown = null
  for (const backend of backends) {
    let session: ort.InferenceSession | null = null
    try {
      session = await ort.InferenceSession.create(modelUrl, {
        executionProviders: backend.providers,
        graphOptimizationLevel: 'all',
      })
      // Validate the backend can actually run (catches GPUs that init but fail
      // at run()) — but only once, to avoid a costly large-model warmup.
      if (!backendValidated) {
        await warmUp(session, warmSize)
        backendValidated = true
      }
      activeBackend = backend.name
      return session
    } catch (err) {
      lastError = err
      try { await session?.release() } catch { /* ignore */ }
      // try the next (more compatible) backend
    }
  }
  throw new Error(
    `Failed to initialize the detection model on this device. ${
      lastError instanceof Error ? lastError.message : String(lastError ?? '')
    }`,
  )
}

function getSession(modelUrl: string): Promise<ort.InferenceSession> {
  let cached = sessionCache.get(modelUrl)
  if (!cached) {
    cached = createSession(modelUrl).catch((err) => {
      // don't cache a failed load — allow a later retry
      sessionCache.delete(modelUrl)
      throw err
    })
    sessionCache.set(modelUrl, cached)
  }
  return cached
}

export function getActiveBackend(): string {
  return activeBackend
}

// Warm only the small (640) model on startup. The large 1024 model is loaded
// lazily when a big photo actually needs it — this keeps peak memory low so
// low-RAM Android devices don't OOM during initial load.
export async function loadModel(onProgress?: (msg: string) => void): Promise<void> {
  onProgress?.('Loading model...')
  await getSession(MODEL_640_URL)
  onProgress?.(`Model ready (${activeBackend})`)
}

function prepareSource(
  image: HTMLImageElement,
  enhance: boolean,
  enhanceOptions?: EnhanceOptions,
): HTMLCanvasElement | HTMLImageElement {
  if (!enhance) {
    return image
  }
  return enhanceImageElement(image, enhanceOptions)
}

async function inferCanvas(
  source: HTMLCanvasElement | HTMLImageElement,
  session: ort.InferenceSession,
  inferenceSize: number,
  offsetX: number,
  offsetY: number,
  regionW: number,
  regionH: number,
): Promise<Detection[]> {
  const { canvas, meta } = letterboxCanvas(source, inferenceSize)
  const tensor = canvasToTensor(canvas, inferenceSize)
  const input = new ort.Tensor('float32', tensor, [1, 3, inferenceSize, inferenceSize])
  const results = await session.run({ images: input })
  const output = results.output.data as Float32Array
  const dets = decodeOutput(output, meta, regionW, regionH)
  return dets.map((d) => ({
    ...d,
    xmin: d.xmin + offsetX,
    ymin: d.ymin + offsetY,
    xmax: d.xmax + offsetX,
    ymax: d.ymax + offsetY,
  }))
}

export function decodeOutput(
  output: Float32Array,
  meta: LetterboxMeta,
  imageW: number,
  imageH: number,
  confThreshold = CONFIDENCE_THRESHOLD,
): Detection[] {
  const rows = output.length / 6
  const raw = []

  for (let i = 0; i < rows; i++) {
    const base = i * 6
    const cx = output[base]
    const cy = output[base + 1]
    const w = output[base + 2]
    const h = output[base + 3]
    const obj = output[base + 4]
    const cls = output[base + 5]
    const confidence = obj * cls
    if (confidence < confThreshold) {
      continue
    }
    const box = mapBoxToOriginal(cx, cy, w, h, meta)
    box.xmin = Math.max(0, Math.min(imageW, box.xmin))
    box.ymin = Math.max(0, Math.min(imageH, box.ymin))
    box.xmax = Math.max(0, Math.min(imageW, box.xmax))
    box.ymax = Math.max(0, Math.min(imageH, box.ymax))
    if (box.xmax <= box.xmin || box.ymax <= box.ymin) {
      continue
    }
    raw.push({ ...box, confidence })
  }

  const filtered = nonMaxSuppression(raw, IOU_THRESHOLD, MAX_DETECTIONS)
  return filtered.map((d, idx) => ({
    ...d,
    id: `det-${idx}-${Date.now()}`,
    groupId: 0,
    confidence: d.confidence,
  }))
}

export async function runDetection(
  image: HTMLImageElement,
  options?: {
    useTiling?: boolean
    autoTile?: boolean
    enhanceImage?: boolean
    enhanceOptions?: EnhanceOptions
    filterOutliers?: boolean
    onProgress?: (msg: string) => void
    onReport?: (r: PostProcessReport) => void
  },
): Promise<Detection[]> {
  await loadModel(options?.onProgress)
  const w = image.naturalWidth
  const h = image.naturalHeight
  const { modelUrl, inferenceSize } = selectModelForImage(w, h)
  // The large model may not be warmed yet (we lazy-load it to save memory).
  if (!sessionCache.has(modelUrl)) {
    options?.onProgress?.('Preparing high-resolution model...')
  }
  const session = await getSession(modelUrl)
  const start = performance.now()

  const enhance = options?.enhanceImage ?? true
  const useTiling =
    options?.useTiling ?? (options?.autoTile !== false && shouldAutoTile(w, h))

  if (useTiling) {
    return runTiledDetection(image, session, inferenceSize, {
      ...options,
      enhanceImage: enhance,
    })
  }
  options?.onProgress?.(enhance ? 'Enhancing image...' : 'Preparing image...')
  const source = prepareSource(image, enhance, options?.enhanceOptions)
  const dets = await inferCanvas(source, session, inferenceSize, 0, 0, w, h)
  const processed = postProcessPipeline(dets, {
    extraOutlierFilter: options?.filterOutliers ?? false,
    wasTiled: false,
    onReport: options?.onReport,
  })
  options?.onProgress?.(`Detected ${processed.length} pipes in ${Math.round(performance.now() - start)}ms`)
  return reassignDetectionIds(processed, 'det').map((d) => ({
    ...d,
    groupId: 0,
    confidence: d.confidence,
  }))
}

// How many tiles may be inferred in flight at once. Tile inference is the
// dominant cost on dense bundles, and the old loop ran every tile strictly
// sequentially. Overlapping tiles lets CPU tensor-prep of the next tile run
// while the previous tile's session.run is in flight (and on WebGPU the GPU
// pipelines the runs). Each in-flight 1024 tensor + output is ~25MB+, so we
// stay sequential on low-RAM phones to avoid OOM.
function tileConcurrency(): number {
  if (isLowMemoryDevice()) return 1
  if (getActiveBackend() === 'webgpu') return 4
  return 2
}

async function runWithConcurrency<T, R>(
  items: readonly T[],
  worker: (item: T) => Promise<R>,
  concurrency: number,
): Promise<R[]> {
  const results: R[] = new Array(items.length)
  let cursor = 0
  const runLane = async (): Promise<void> => {
    while (cursor < items.length) {
      const index = cursor
      cursor += 1
      results[index] = await worker(items[index])
    }
  }
  const lanes = Math.max(1, Math.min(concurrency, items.length))
  await Promise.all(Array.from({ length: lanes }, runLane))
  return results
}

async function runTiledDetection(
  image: HTMLImageElement,
  session: ort.InferenceSession,
  inferenceSize: number,
  options?: {
    enhanceImage?: boolean
    enhanceOptions?: EnhanceOptions
    filterOutliers?: boolean
    onProgress?: (msg: string) => void
    onReport?: (r: PostProcessReport) => void
  },
): Promise<Detection[]> {
  const onProgress = options?.onProgress
  const w = image.naturalWidth
  const h = image.naturalHeight
  const grid = suggestTileGrid(w, h)
  const overlap = TILE_OVERLAP
  const tileW = w / grid
  const tileH = h / grid
  const all: Detection[] = []

  onProgress?.(`Enhancing + tiling ${grid}x${grid}...`)
  const enhanced = (options?.enhanceImage ?? true)
    ? enhanceImageElement(image, options?.enhanceOptions)
    : image

  // Build tile rects (unchanged geometry), then infer with a memory-aware
  // concurrency limit instead of a strictly sequential loop.
  const rects: Array<{ x1: number; y1: number; cropW: number; cropH: number }> = []
  for (let gy = 0; gy < grid; gy++) {
    for (let gx = 0; gx < grid; gx++) {
      const x1 = Math.max(0, gx * tileW - (tileW * overlap * (gx > 0 ? 1 : 0)))
      const y1 = Math.max(0, gy * tileH - (tileH * overlap * (gy > 0 ? 1 : 0)))
      const x2 = Math.min(w, (gx + 1) * tileW + (tileW * overlap * (gx < grid - 1 ? 1 : 0)))
      const y2 = Math.min(h, (gy + 1) * tileH + (tileH * overlap * (gy < grid - 1 ? 1 : 0)))
      rects.push({ x1, y1, cropW: x2 - x1, cropH: y2 - y1 })
    }
  }
  const totalTiles = rects.length
  let done = 0
  const tileBatches = await runWithConcurrency(
    rects,
    async (r) => {
      const tileCanvas = document.createElement('canvas')
      tileCanvas.width = r.cropW
      tileCanvas.height = r.cropH
      const ctx = tileCanvas.getContext('2d')!
      ctx.drawImage(enhanced, r.x1, r.y1, r.cropW, r.cropH, 0, 0, r.cropW, r.cropH)
      const dets = await inferCanvas(
        tileCanvas,
        session,
        inferenceSize,
        r.x1,
        r.y1,
        r.cropW,
        r.cropH,
      )
      done += 1
      onProgress?.(`Tile ${done}/${totalTiles}...`)
      return dets
    },
    tileConcurrency(),
  )
  for (const dets of tileBatches) all.push(...dets)

  const merged = reassignDetectionIds(
    postProcessPipeline(all, {
      extraOutlierFilter: options?.filterOutliers ?? false,
      wasTiled: true,
      onReport: options?.onReport,
    }),
    'pipe',
  ).map((d) => ({ ...d, groupId: 0 }))
  onProgress?.(`Tiled detection: ${merged.length} pipes`)
  return merged
}