Khunndev Cursor commited on
Commit
d600757
·
1 Parent(s): 1596a62

Harden model loading for low-end Android (single-thread WASM, WebGPU pre-check + warmup, lazy load, retry UI)

Browse files
frontend/src/App.tsx CHANGED
@@ -40,6 +40,7 @@ export default function App() {
40
 
41
  // ui state
42
  const [modelReady, setModelReady] = useState(false)
 
43
  const [status, setStatus] = useState('')
44
  const [busy, setBusy] = useState(false)
45
 
@@ -48,10 +49,20 @@ export default function App() {
48
 
49
  const counts = countByGroup(detections, groups)
50
 
51
- useEffect(() => {
 
 
52
  loadModel(setStatus)
53
  .then(() => { setModelReady(true); setStatus('') })
54
- .catch((err: unknown) => setStatus(String(err)))
 
 
 
 
 
 
 
 
55
  }, [])
56
 
57
  // -------------------------------------------------------------------------
@@ -183,6 +194,8 @@ export default function App() {
183
  <StepCapture
184
  lang={lang}
185
  modelReady={modelReady}
 
 
186
  onCamera={() => cameraRef.current?.click()}
187
  onGallery={() => fileRef.current?.click()}
188
  />
 
40
 
41
  // ui state
42
  const [modelReady, setModelReady] = useState(false)
43
+ const [modelError, setModelError] = useState('')
44
  const [status, setStatus] = useState('')
45
  const [busy, setBusy] = useState(false)
46
 
 
49
 
50
  const counts = countByGroup(detections, groups)
51
 
52
+ const initModel = () => {
53
+ setModelError('')
54
+ setModelReady(false)
55
  loadModel(setStatus)
56
  .then(() => { setModelReady(true); setStatus('') })
57
+ .catch((err: unknown) => {
58
+ setModelError(err instanceof Error ? err.message : String(err))
59
+ setStatus('')
60
+ })
61
+ }
62
+
63
+ useEffect(() => {
64
+ initModel()
65
+ // eslint-disable-next-line react-hooks/exhaustive-deps
66
  }, [])
67
 
68
  // -------------------------------------------------------------------------
 
194
  <StepCapture
195
  lang={lang}
196
  modelReady={modelReady}
197
+ modelError={modelError}
198
+ onRetryModel={initModel}
199
  onCamera={() => cameraRef.current?.click()}
200
  onGallery={() => fileRef.current?.click()}
201
  />
frontend/src/components/StepCapture.tsx CHANGED
@@ -1,15 +1,18 @@
1
- import { Camera, ImagePlus } from 'lucide-react'
2
  import { t } from '../lib/i18n'
3
  import type { Lang } from '../lib/types'
4
 
5
  interface Props {
6
  lang: Lang
7
  modelReady: boolean
 
 
8
  onCamera: () => void
9
  onGallery: () => void
10
  }
11
 
12
- export function StepCapture({ lang, modelReady, onCamera, onGallery }: Props) {
 
13
  return (
14
  <div className="relative flex flex-1 flex-col overflow-hidden">
15
  {/* Background ambient glow */}
@@ -64,28 +67,61 @@ export function StepCapture({ lang, modelReady, onCamera, onGallery }: Props) {
64
  </div>
65
 
66
  {/* Model status badge */}
67
- <div
68
- className={`flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium transition-colors duration-500 ${
69
- modelReady
70
- ? 'bg-emerald-500/15 text-emerald-300'
71
- : 'bg-amber-500/15 text-amber-300'
72
- }`}
73
- >
74
- <span
75
- className={`h-1.5 w-1.5 rounded-full ${
76
- modelReady ? 'bg-emerald-400' : 'animate-pulse bg-amber-400'
 
 
 
 
 
77
  }`}
78
- />
79
- {modelReady ? t(lang, 'modelReady') : t(lang, 'loadingModel')}
80
- </div>
 
 
 
 
 
 
81
  </div>
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  {/* CTA buttons */}
84
  <div className="w-full max-w-sm space-y-3">
85
  {/* Primary: Camera */}
86
  <button
87
  type="button"
88
- className="relative flex h-[58px] w-full items-center justify-center gap-3 overflow-hidden rounded-2xl text-base font-bold text-white shadow-xl transition-all duration-150 active:scale-[0.97]"
 
89
  style={{
90
  background: 'linear-gradient(135deg, #2563eb 0%, #1d4ed8 50%, #1e40af 100%)',
91
  boxShadow: '0 8px 32px rgba(37,99,235,0.45)',
@@ -101,7 +137,8 @@ export function StepCapture({ lang, modelReady, onCamera, onGallery }: Props) {
101
  {/* Secondary: Gallery */}
102
  <button
103
  type="button"
104
- className="flex h-[58px] w-full items-center justify-center gap-3 rounded-2xl border border-white/12 bg-white/6 text-base font-medium text-white/85 backdrop-blur-sm transition-all duration-150 active:scale-[0.97] active:bg-white/10"
 
105
  onClick={onGallery}
106
  >
107
  <ImagePlus size={22} strokeWidth={2} />
 
1
+ import { AlertTriangle, Camera, ImagePlus, RotateCcw } from 'lucide-react'
2
  import { t } from '../lib/i18n'
3
  import type { Lang } from '../lib/types'
4
 
5
  interface Props {
6
  lang: Lang
7
  modelReady: boolean
8
+ modelError?: string
9
+ onRetryModel?: () => void
10
  onCamera: () => void
11
  onGallery: () => void
12
  }
13
 
14
+ export function StepCapture({ lang, modelReady, modelError, onRetryModel, onCamera, onGallery }: Props) {
15
+ const hasError = Boolean(modelError)
16
  return (
17
  <div className="relative flex flex-1 flex-col overflow-hidden">
18
  {/* Background ambient glow */}
 
67
  </div>
68
 
69
  {/* Model status badge */}
70
+ {hasError ? (
71
+ <button
72
+ type="button"
73
+ onClick={onRetryModel}
74
+ className="flex items-center gap-1.5 rounded-full bg-red-500/15 px-3 py-1 text-xs font-medium text-red-300 transition-all duration-150 active:scale-95"
75
+ >
76
+ <RotateCcw size={12} />
77
+ {t(lang, 'retry')}
78
+ </button>
79
+ ) : (
80
+ <div
81
+ className={`flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium transition-colors duration-500 ${
82
+ modelReady
83
+ ? 'bg-emerald-500/15 text-emerald-300'
84
+ : 'bg-amber-500/15 text-amber-300'
85
  }`}
86
+ >
87
+ <span
88
+ className={`h-1.5 w-1.5 rounded-full ${
89
+ modelReady ? 'bg-emerald-400' : 'animate-pulse bg-amber-400'
90
+ }`}
91
+ />
92
+ {modelReady ? t(lang, 'modelReady') : t(lang, 'loadingModel')}
93
+ </div>
94
+ )}
95
  </div>
96
 
97
+ {/* Model load error */}
98
+ {hasError && (
99
+ <div className="mb-4 w-full max-w-sm rounded-2xl border border-red-500/25 bg-red-500/10 p-4">
100
+ <div className="flex items-start gap-2.5">
101
+ <AlertTriangle size={18} className="mt-0.5 shrink-0 text-red-400" />
102
+ <div className="min-w-0">
103
+ <p className="text-sm font-semibold text-red-200">{t(lang, 'modelErrorTitle')}</p>
104
+ <p className="mt-1 break-words text-xs text-red-300/70">{modelError}</p>
105
+ <button
106
+ type="button"
107
+ onClick={onRetryModel}
108
+ className="mt-3 flex items-center gap-1.5 rounded-xl bg-red-500/20 px-3 py-1.5 text-xs font-semibold text-red-100 transition-all duration-150 active:scale-95"
109
+ >
110
+ <RotateCcw size={13} />
111
+ {t(lang, 'retry')}
112
+ </button>
113
+ </div>
114
+ </div>
115
+ </div>
116
+ )}
117
+
118
  {/* CTA buttons */}
119
  <div className="w-full max-w-sm space-y-3">
120
  {/* Primary: Camera */}
121
  <button
122
  type="button"
123
+ disabled={hasError}
124
+ className="relative flex h-[58px] w-full items-center justify-center gap-3 overflow-hidden rounded-2xl text-base font-bold text-white shadow-xl transition-all duration-150 active:scale-[0.97] disabled:opacity-50"
125
  style={{
126
  background: 'linear-gradient(135deg, #2563eb 0%, #1d4ed8 50%, #1e40af 100%)',
127
  boxShadow: '0 8px 32px rgba(37,99,235,0.45)',
 
137
  {/* Secondary: Gallery */}
138
  <button
139
  type="button"
140
+ disabled={hasError}
141
+ className="flex h-[58px] w-full items-center justify-center gap-3 rounded-2xl border border-white/12 bg-white/6 text-base font-medium text-white/85 backdrop-blur-sm transition-all duration-150 active:scale-[0.97] active:bg-white/10 disabled:opacity-50"
142
  onClick={onGallery}
143
  >
144
  <ImagePlus size={22} strokeWidth={2} />
frontend/src/lib/i18n.ts CHANGED
@@ -21,6 +21,8 @@ const messages = {
21
  newPhoto: 'Choose a different photo',
22
  loadingModel: 'Loading model...',
23
  modelReady: 'Model ready',
 
 
24
  processing: 'Processing...',
25
  pleaseWait: 'This may take a moment on large photos.',
26
  total: 'Total pipes',
@@ -69,6 +71,8 @@ const messages = {
69
  newPhoto: 'เลือกรูปอื่น',
70
  loadingModel: 'กำลังโหลดโมเดล...',
71
  modelReady: 'โมเดลพร้อมใช้งาน',
 
 
72
  processing: 'กำลังประมวลผล...',
73
  pleaseWait: 'รูปขนาดใหญ่อาจใช้เวลาสักครู่',
74
  total: 'จำนวนท่อรวม',
 
21
  newPhoto: 'Choose a different photo',
22
  loadingModel: 'Loading model...',
23
  modelReady: 'Model ready',
24
+ modelErrorTitle: 'Could not load the AI model',
25
+ retry: 'Retry',
26
  processing: 'Processing...',
27
  pleaseWait: 'This may take a moment on large photos.',
28
  total: 'Total pipes',
 
71
  newPhoto: 'เลือกรูปอื่น',
72
  loadingModel: 'กำลังโหลดโมเดล...',
73
  modelReady: 'โมเดลพร้อมใช้งาน',
74
+ modelErrorTitle: 'โหลดโมเดล AI ไม่สำเร็จ',
75
+ retry: 'ลองใหม่',
76
  processing: 'กำลังประมวลผล...',
77
  pleaseWait: 'รูปขนาดใหญ่อาจใช้เวลาสักครู่',
78
  total: 'จำนวนท่อรวม',
frontend/src/lib/inference.ts CHANGED
@@ -13,34 +13,101 @@ import type { Detection, LetterboxMeta } from './types'
13
 
14
  ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.26.0/dist/'
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  let sessionCache = new Map<string, Promise<ort.InferenceSession>>()
17
  let activeBackend = 'loading'
18
 
 
 
 
 
 
19
  async function createSession(modelUrl: string): Promise<ort.InferenceSession> {
20
- const backends: Array<{ name: string; providers: ort.InferenceSession.SessionOptions['executionProviders'] }> = [
21
- { name: 'webgpu', providers: ['webgpu', 'wasm'] },
22
- { name: 'wasm', providers: ['wasm'] },
23
- ]
 
 
 
24
 
 
25
  for (const backend of backends) {
 
26
  try {
27
- const session = await ort.InferenceSession.create(modelUrl, {
28
  executionProviders: backend.providers,
29
  graphOptimizationLevel: 'all',
30
  })
 
 
31
  activeBackend = backend.name
32
  return session
33
- } catch {
34
- continue
 
 
35
  }
36
  }
37
- throw new Error('Failed to initialize ONNX Runtime')
 
 
 
 
38
  }
39
 
40
  function getSession(modelUrl: string): Promise<ort.InferenceSession> {
41
  let cached = sessionCache.get(modelUrl)
42
  if (!cached) {
43
- cached = createSession(modelUrl)
 
 
 
 
44
  sessionCache.set(modelUrl, cached)
45
  }
46
  return cached
@@ -50,10 +117,13 @@ export function getActiveBackend(): string {
50
  return activeBackend
51
  }
52
 
 
 
 
53
  export async function loadModel(onProgress?: (msg: string) => void): Promise<void> {
54
- onProgress?.('Loading models...')
55
- await Promise.all([getSession(MODEL_URL), getSession(MODEL_640_URL)])
56
- onProgress?.(`Models ready (${activeBackend})`)
57
  }
58
 
59
  function prepareSource(
@@ -160,6 +230,10 @@ export async function runDetection(
160
  const w = image.naturalWidth
161
  const h = image.naturalHeight
162
  const { modelUrl, inferenceSize } = selectModelForImage(w, h)
 
 
 
 
163
  const session = await getSession(modelUrl)
164
  const start = performance.now()
165
 
 
13
 
14
  ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.26.0/dist/'
15
 
16
+ // ---------------------------------------------------------------------------
17
+ // Backend capability detection (important for low-end Android devices)
18
+ // ---------------------------------------------------------------------------
19
+
20
+ // Multi-threaded WASM needs SharedArrayBuffer, which is only available when the
21
+ // page is cross-origin isolated (COOP/COEP). Static hosts (e.g. HF Spaces) don't
22
+ // set those headers, so we must run single-threaded — otherwise ORT may try to
23
+ // spawn workers and crash on weak devices.
24
+ function resolveThreadCount(): number {
25
+ const hasSAB = typeof SharedArrayBuffer !== 'undefined'
26
+ const isolated = typeof globalThis !== 'undefined'
27
+ && Boolean((globalThis as { crossOriginIsolated?: boolean }).crossOriginIsolated)
28
+ if (!hasSAB || !isolated) return 1
29
+ const cores = typeof navigator !== 'undefined' ? navigator.hardwareConcurrency || 2 : 2
30
+ return Math.max(1, Math.min(4, cores))
31
+ }
32
+
33
+ ort.env.wasm.numThreads = resolveThreadCount()
34
+ ort.env.wasm.simd = true
35
+
36
+ // WebGPU often *creates* a session on cheap Android GPUs but then throws at
37
+ // run() time. We pre-check for a usable adapter and additionally warm up each
38
+ // session so a broken backend is rejected before we depend on it.
39
+ let webgpuChecked = false
40
+ let webgpuOk = false
41
+ async function isWebgpuUsable(): Promise<boolean> {
42
+ if (webgpuChecked) return webgpuOk
43
+ webgpuChecked = true
44
+ try {
45
+ const gpu = (navigator as unknown as { gpu?: { requestAdapter(): Promise<unknown> } }).gpu
46
+ if (!gpu) { webgpuOk = false; return false }
47
+ const adapter = await gpu.requestAdapter()
48
+ webgpuOk = Boolean(adapter)
49
+ } catch {
50
+ webgpuOk = false
51
+ }
52
+ return webgpuOk
53
+ }
54
+
55
+ // Map each model to the input size used to warm it up.
56
+ const MODEL_WARMUP_SIZE: Record<string, number> = {
57
+ [MODEL_URL]: 1024,
58
+ [MODEL_640_URL]: 640,
59
+ }
60
+
61
  let sessionCache = new Map<string, Promise<ort.InferenceSession>>()
62
  let activeBackend = 'loading'
63
 
64
+ async function warmUp(session: ort.InferenceSession, size: number): Promise<void> {
65
+ const dummy = new ort.Tensor('float32', new Float32Array(3 * size * size), [1, 3, size, size])
66
+ await session.run({ images: dummy })
67
+ }
68
+
69
  async function createSession(modelUrl: string): Promise<ort.InferenceSession> {
70
+ const warmSize = MODEL_WARMUP_SIZE[modelUrl] ?? 640
71
+
72
+ const backends: Array<{ name: string; providers: ort.InferenceSession.SessionOptions['executionProviders'] }> = []
73
+ if (await isWebgpuUsable()) {
74
+ backends.push({ name: 'webgpu', providers: ['webgpu', 'wasm'] })
75
+ }
76
+ backends.push({ name: 'wasm', providers: ['wasm'] })
77
 
78
+ let lastError: unknown = null
79
  for (const backend of backends) {
80
+ let session: ort.InferenceSession | null = null
81
  try {
82
+ session = await ort.InferenceSession.create(modelUrl, {
83
  executionProviders: backend.providers,
84
  graphOptimizationLevel: 'all',
85
  })
86
+ // Validate the backend actually runs — catches GPUs that init but fail at run().
87
+ await warmUp(session, warmSize)
88
  activeBackend = backend.name
89
  return session
90
+ } catch (err) {
91
+ lastError = err
92
+ try { await session?.release() } catch { /* ignore */ }
93
+ // try the next (more compatible) backend
94
  }
95
  }
96
+ throw new Error(
97
+ `Failed to initialize the detection model on this device. ${
98
+ lastError instanceof Error ? lastError.message : String(lastError ?? '')
99
+ }`,
100
+ )
101
  }
102
 
103
  function getSession(modelUrl: string): Promise<ort.InferenceSession> {
104
  let cached = sessionCache.get(modelUrl)
105
  if (!cached) {
106
+ cached = createSession(modelUrl).catch((err) => {
107
+ // don't cache a failed load — allow a later retry
108
+ sessionCache.delete(modelUrl)
109
+ throw err
110
+ })
111
  sessionCache.set(modelUrl, cached)
112
  }
113
  return cached
 
117
  return activeBackend
118
  }
119
 
120
+ // Warm only the small (640) model on startup. The large 1024 model is loaded
121
+ // lazily when a big photo actually needs it — this keeps peak memory low so
122
+ // low-RAM Android devices don't OOM during initial load.
123
  export async function loadModel(onProgress?: (msg: string) => void): Promise<void> {
124
+ onProgress?.('Loading model...')
125
+ await getSession(MODEL_640_URL)
126
+ onProgress?.(`Model ready (${activeBackend})`)
127
  }
128
 
129
  function prepareSource(
 
230
  const w = image.naturalWidth
231
  const h = image.naturalHeight
232
  const { modelUrl, inferenceSize } = selectModelForImage(w, h)
233
+ // The large model may not be warmed yet (we lazy-load it to save memory).
234
+ if (!sessionCache.has(modelUrl)) {
235
+ options?.onProgress?.('Preparing high-resolution model...')
236
+ }
237
  const session = await getSession(modelUrl)
238
  const start = performance.now()
239