Khunndev Cursor commited on
Commit
06bdaca
·
1 Parent(s): d600757

Add server-side detection fallback for devices that can't run the model locally

Browse files
Dockerfile CHANGED
@@ -11,9 +11,13 @@ FROM python:3.10-slim
11
  LABEL maintainer="NPI Pipe Count"
12
  ENV PYTHONUNBUFFERED=1
13
  WORKDIR /app
 
 
 
 
14
  COPY requirements-server.txt .
15
  RUN pip install --no-cache-dir -r requirements-server.txt
16
- COPY main.py .
17
  COPY --from=frontend-build /frontend/dist ./static
18
  RUN useradd -m appuser && chown -R appuser:appuser /app
19
  USER appuser
 
11
  LABEL maintainer="NPI Pipe Count"
12
  ENV PYTHONUNBUFFERED=1
13
  WORKDIR /app
14
+ # Native libs required by onnxruntime (libgomp1) and opencv-python-headless (libglib2.0-0)
15
+ RUN apt-get update \
16
+ && apt-get install -y --no-install-recommends libgomp1 libglib2.0-0 \
17
+ && rm -rf /var/lib/apt/lists/*
18
  COPY requirements-server.txt .
19
  RUN pip install --no-cache-dir -r requirements-server.txt
20
+ COPY main.py detect.py ./
21
  COPY --from=frontend-build /frontend/dist ./static
22
  RUN useradd -m appuser && chown -R appuser:appuser /app
23
  USER appuser
detect.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Server-side ONNX pipe detection (CPU).
2
+
3
+ Used as a fallback when a client device cannot load / run the in-browser model.
4
+ Mirrors the browser inference pipeline (letterbox -> ONNX -> decode -> NMS) so
5
+ results are consistent regardless of where inference runs.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from pathlib import Path
11
+ from threading import Lock
12
+ from typing import Any
13
+
14
+ STATIC_PATH = Path(__file__).resolve().parent / "static"
15
+ MODEL_DIR = STATIC_PATH / "models"
16
+
17
+ INFERENCE_SIZE = 1024
18
+ INFERENCE_SIZE_SMALL = 640
19
+ CONF_THRESHOLD = 0.6
20
+ IOU_THRESHOLD = 0.45
21
+ MAX_DET = 4000
22
+ TILE_OVERLAP = 0.2
23
+
24
+ _sessions: dict[str, Any] = {}
25
+ _session_lock = Lock()
26
+ _active_backend = "cpu"
27
+
28
+
29
+ def is_available() -> bool:
30
+ """True when server-side inference can run (deps + model files present)."""
31
+ try:
32
+ import numpy # noqa: F401
33
+ import onnxruntime # noqa: F401
34
+ import cv2 # noqa: F401
35
+ except Exception:
36
+ return False
37
+ return (MODEL_DIR / "countmodel.onnx").is_file() or (MODEL_DIR / "countmodel-640.onnx").is_file()
38
+
39
+
40
+ def get_active_backend() -> str:
41
+ return _active_backend
42
+
43
+
44
+ def _get_session(model_path: Path):
45
+ global _active_backend
46
+ key = str(model_path)
47
+ sess = _sessions.get(key)
48
+ if sess is not None:
49
+ return sess
50
+ with _session_lock:
51
+ sess = _sessions.get(key)
52
+ if sess is not None:
53
+ return sess
54
+ import onnxruntime as ort
55
+
56
+ opts = ort.SessionOptions()
57
+ cores = os.cpu_count() or 2
58
+ opts.intra_op_num_threads = max(1, min(4, cores))
59
+ opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
60
+ providers = ort.get_available_providers()
61
+ # Prefer GPU if present on the host, else CPU.
62
+ chosen = [p for p in ("CUDAExecutionProvider", "CPUExecutionProvider") if p in providers]
63
+ if not chosen:
64
+ chosen = ["CPUExecutionProvider"]
65
+ _active_backend = "cuda" if chosen[0] == "CUDAExecutionProvider" else "cpu"
66
+ sess = ort.InferenceSession(str(model_path), sess_options=opts, providers=chosen)
67
+ _sessions[key] = sess
68
+ return sess
69
+
70
+
71
+ def _megapixels(w: int, h: int) -> float:
72
+ return (w * h) / 1_000_000
73
+
74
+
75
+ def _suggest_tile_grid(w: int, h: int) -> int:
76
+ mp = _megapixels(w, h)
77
+ if mp >= 8:
78
+ return 5
79
+ if mp >= 4:
80
+ return 4
81
+ if mp >= 2:
82
+ return 3
83
+ return 2
84
+
85
+
86
+ def _should_auto_tile(w: int, h: int) -> bool:
87
+ return _megapixels(w, h) >= 2 or max(w, h) > 2000
88
+
89
+
90
+ def _select_model(w: int, h: int) -> tuple[Path, int]:
91
+ if max(w, h) <= 1200:
92
+ small = MODEL_DIR / "countmodel-640.onnx"
93
+ if small.is_file():
94
+ return small, INFERENCE_SIZE_SMALL
95
+ big = MODEL_DIR / "countmodel.onnx"
96
+ if big.is_file():
97
+ return big, INFERENCE_SIZE
98
+ # fall back to whichever exists
99
+ return (MODEL_DIR / "countmodel-640.onnx", INFERENCE_SIZE_SMALL)
100
+
101
+
102
+ def _letterbox(img, size: int):
103
+ import cv2
104
+ import numpy as np
105
+
106
+ h, w = img.shape[:2]
107
+ scale = min(size / w, size / h)
108
+ new_w, new_h = int(round(w * scale)), int(round(h * scale))
109
+ pad_x = (size - new_w) // 2
110
+ pad_y = (size - new_h) // 2
111
+ out = np.full((size, size, 3), 114, dtype=np.uint8)
112
+ resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)
113
+ out[pad_y : pad_y + new_h, pad_x : pad_x + new_w] = resized
114
+ tensor = out[:, :, ::-1].astype(np.float32) / 255.0
115
+ chw = np.transpose(tensor, (2, 0, 1))[None, ...]
116
+ return chw, {"scale": scale, "pad_x": pad_x, "pad_y": pad_y}
117
+
118
+
119
+ def _iou(a, b) -> float:
120
+ x1 = max(a[0], b[0])
121
+ y1 = max(a[1], b[1])
122
+ x2 = min(a[2], b[2])
123
+ y2 = min(a[3], b[3])
124
+ inter = max(0, x2 - x1) * max(0, y2 - y1)
125
+ area_a = (a[2] - a[0]) * (a[3] - a[1])
126
+ area_b = (b[2] - b[0]) * (b[3] - b[1])
127
+ return inter / (area_a + area_b - inter + 1e-6)
128
+
129
+
130
+ def _nms(boxes, scores, iou_thres=IOU_THRESHOLD, max_det=MAX_DET):
131
+ import numpy as np
132
+
133
+ order = np.argsort(scores)[::-1]
134
+ keep = []
135
+ while order.size > 0 and len(keep) < max_det:
136
+ i = int(order[0])
137
+ keep.append(i)
138
+ if order.size == 1:
139
+ break
140
+ rest = order[1:]
141
+ ious = np.array([_iou(boxes[i], boxes[j]) for j in rest])
142
+ order = rest[ious <= iou_thres]
143
+ return keep
144
+
145
+
146
+ def _filter_outliers(boxes):
147
+ import numpy as np
148
+
149
+ if len(boxes) < 3:
150
+ return list(range(len(boxes)))
151
+ areas = [(b[2] - b[0]) * (b[3] - b[1]) for b in boxes]
152
+ median = float(np.median(areas))
153
+ return [i for i, a in enumerate(areas) if median * 0.25 <= a <= median * 4.0]
154
+
155
+
156
+ def _decode(output, meta, img_w, img_h, offset_x=0, offset_y=0):
157
+ boxes, scores = [], []
158
+ for row in output.reshape(-1, 6):
159
+ cx, cy, w, h, obj, cls = row
160
+ conf = float(obj * cls)
161
+ if conf < CONF_THRESHOLD:
162
+ continue
163
+ x1 = (cx - w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
164
+ y1 = (cy - h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
165
+ x2 = (cx + w / 2 - meta["pad_x"]) / meta["scale"] + offset_x
166
+ y2 = (cy + h / 2 - meta["pad_y"]) / meta["scale"] + offset_y
167
+ x1, y1 = max(0, x1), max(0, y1)
168
+ x2, y2 = min(img_w, x2), min(img_h, y2)
169
+ if x2 <= x1 or y2 <= y1:
170
+ continue
171
+ boxes.append([x1, y1, x2, y2])
172
+ scores.append(conf)
173
+ return boxes, scores
174
+
175
+
176
+ def detect_bytes(
177
+ image_bytes: bytes,
178
+ use_tiling: bool | None = None,
179
+ auto_tile: bool = True,
180
+ filter_outliers_flag: bool = False,
181
+ ) -> dict[str, Any]:
182
+ import time
183
+
184
+ import cv2
185
+ import numpy as np
186
+
187
+ arr = np.frombuffer(image_bytes, dtype=np.uint8)
188
+ img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
189
+ if img is None:
190
+ raise ValueError("Could not decode image")
191
+
192
+ h, w = img.shape[:2]
193
+ model_path, infer_size = _select_model(w, h)
194
+ session = _get_session(model_path)
195
+
196
+ tile = use_tiling if use_tiling is not None else (auto_tile and _should_auto_tile(w, h))
197
+ t0 = time.perf_counter()
198
+
199
+ if tile:
200
+ grid = _suggest_tile_grid(w, h)
201
+ tile_w = w / grid
202
+ tile_h = h / grid
203
+ all_boxes: list = []
204
+ all_scores: list = []
205
+ for gy in range(grid):
206
+ for gx in range(grid):
207
+ x1 = max(0, gx * tile_w - (tile_w * TILE_OVERLAP * (gx > 0)))
208
+ y1 = max(0, gy * tile_h - (tile_h * TILE_OVERLAP * (gy > 0)))
209
+ x2 = min(w, (gx + 1) * tile_w + (tile_w * TILE_OVERLAP * (gx < grid - 1)))
210
+ y2 = min(h, (gy + 1) * tile_h + (tile_h * TILE_OVERLAP * (gy < grid - 1)))
211
+ crop = img[int(y1) : int(y2), int(x1) : int(x2)]
212
+ tensor, meta = _letterbox(crop, infer_size)
213
+ out = session.run(None, {"images": tensor})[0]
214
+ boxes, scores = _decode(out, meta, w, h, int(x1), int(y1))
215
+ all_boxes.extend(boxes)
216
+ all_scores.extend(scores)
217
+ boxes, scores = all_boxes, all_scores
218
+ mode = f"tiling {grid}x{grid}"
219
+ else:
220
+ tensor, meta = _letterbox(img, infer_size)
221
+ out = session.run(None, {"images": tensor})[0]
222
+ boxes, scores = _decode(out, meta, w, h)
223
+ mode = "single frame"
224
+
225
+ if boxes:
226
+ keep = _nms(boxes, scores)
227
+ boxes = [boxes[i] for i in keep]
228
+ scores = [scores[i] for i in keep]
229
+ if filter_outliers_flag:
230
+ keep2 = _filter_outliers(boxes)
231
+ boxes = [boxes[i] for i in keep2]
232
+ scores = [scores[i] for i in keep2]
233
+
234
+ ms = (time.perf_counter() - t0) * 1000
235
+ detections = [
236
+ {
237
+ "xmin": float(b[0]),
238
+ "ymin": float(b[1]),
239
+ "xmax": float(b[2]),
240
+ "ymax": float(b[3]),
241
+ "confidence": float(s),
242
+ }
243
+ for b, s in zip(boxes, scores)
244
+ ]
245
+ return {
246
+ "detections": detections,
247
+ "count": len(detections),
248
+ "width": w,
249
+ "height": h,
250
+ "ms": round(ms),
251
+ "model": model_path.name,
252
+ "mode": mode,
253
+ "backend": f"server-{get_active_backend()}",
254
+ }
frontend/src/App.tsx CHANGED
@@ -1,6 +1,7 @@
1
  import { useEffect, useRef, useState } from 'react'
2
  import { assignDiameterGroups, countByGroup } from './lib/clustering'
3
  import { getActiveBackend, loadModel, runDetection } from './lib/inference'
 
4
  import { t } from './lib/i18n'
5
  import type { Detection, DiameterGroup, Lang } from './lib/types'
6
  import { StepCapture } from './components/StepCapture'
@@ -10,6 +11,13 @@ import { StepResults } from './components/StepResults'
10
 
11
  type Step = 'capture' | 'preview' | 'counting' | 'results'
12
 
 
 
 
 
 
 
 
13
  const STEPS: Step[] = ['capture', 'preview', 'counting', 'results']
14
 
15
  export default function App() {
@@ -27,6 +35,7 @@ export default function App() {
27
  // image
28
  const [image, setImage] = useState<HTMLImageElement | null>(null)
29
  const [imageSrc, setImageSrc] = useState('')
 
30
  const [imageDims, setImageDims] = useState({ w: 0, h: 0 })
31
 
32
  // results
@@ -39,8 +48,9 @@ export default function App() {
39
  const [filterOutliers, setFilterOutliers] = useState(false)
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,19 +59,37 @@ export default function App() {
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
 
@@ -74,6 +102,7 @@ export default function App() {
74
  img.onload = () => {
75
  setImage(img)
76
  setImageSrc(url)
 
77
  setImageDims({ w: img.naturalWidth, h: img.naturalHeight })
78
  setDetections([])
79
  setGroups([])
@@ -83,28 +112,53 @@ export default function App() {
83
  }
84
 
85
  // -------------------------------------------------------------------------
86
- // counting
87
  // -------------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
88
  const runCount = async () => {
89
  if (!image) return
90
  setBusy(true)
91
  setStatus(t(lang, 'processing'))
92
  navigate('counting')
93
  try {
94
- const dets = await runDetection(image, {
95
- useTiling,
96
- enhanceImage: false,
97
- filterOutliers,
98
- autoTile: !useTiling,
99
- onProgress: setStatus,
100
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  const clustered = assignDiameterGroups(dets, groupCount, lang)
102
  setDetections(clustered.detections)
103
  setGroups(clustered.groups)
104
- setStatus(`Done (${getActiveBackend()})`)
105
  navigate('results')
106
  } catch (err) {
107
- setStatus(String(err))
108
  navigate('preview')
109
  } finally {
110
  setBusy(false)
@@ -127,6 +181,7 @@ export default function App() {
127
  setGroups([])
128
  setImage(null)
129
  setImageSrc('')
 
130
  }
131
 
132
  // -------------------------------------------------------------------------
@@ -150,7 +205,13 @@ export default function App() {
150
  <img src="/icon.svg" alt="" className="h-7 w-7 rounded-xl" />
151
  <span
152
  className={`absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full border-2 border-[var(--bg)] transition-colors duration-700 ${
153
- modelReady ? 'bg-emerald-400' : 'animate-pulse bg-amber-400'
 
 
 
 
 
 
154
  }`}
155
  />
156
  </div>
@@ -193,9 +254,9 @@ export default function App() {
193
  {step === 'capture' && (
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
  />
@@ -207,7 +268,7 @@ export default function App() {
207
  imageSrc={imageSrc}
208
  imageDims={imageDims}
209
  busy={busy}
210
- modelReady={modelReady}
211
  groupCount={groupCount}
212
  useTiling={useTiling}
213
  filterOutliers={filterOutliers}
 
1
  import { useEffect, useRef, useState } from 'react'
2
  import { assignDiameterGroups, countByGroup } from './lib/clustering'
3
  import { getActiveBackend, loadModel, runDetection } from './lib/inference'
4
+ import { isServerDetectAvailable, serverDetect } from './lib/serverDetect'
5
  import { t } from './lib/i18n'
6
  import type { Detection, DiameterGroup, Lang } from './lib/types'
7
  import { StepCapture } from './components/StepCapture'
 
11
 
12
  type Step = 'capture' | 'preview' | 'counting' | 'results'
13
 
14
+ // Which inference engine the app will use.
15
+ // - checking: still probing capabilities
16
+ // - local: in-browser ONNX (WebGPU/WASM)
17
+ // - server: local unavailable, server-side fallback reachable
18
+ // - none: neither works (offline + can't load locally)
19
+ type Engine = 'checking' | 'local' | 'server' | 'none'
20
+
21
  const STEPS: Step[] = ['capture', 'preview', 'counting', 'results']
22
 
23
  export default function App() {
 
35
  // image
36
  const [image, setImage] = useState<HTMLImageElement | null>(null)
37
  const [imageSrc, setImageSrc] = useState('')
38
+ const [imageFile, setImageFile] = useState<File | null>(null)
39
  const [imageDims, setImageDims] = useState({ w: 0, h: 0 })
40
 
41
  // results
 
48
  const [filterOutliers, setFilterOutliers] = useState(false)
49
 
50
  // ui state
51
+ const [engine, setEngine] = useState<Engine>('checking')
52
  const [modelError, setModelError] = useState('')
53
+ const [serverAvailable, setServerAvailable] = useState(false)
54
  const [status, setStatus] = useState('')
55
  const [busy, setBusy] = useState(false)
56
 
 
59
 
60
  const counts = countByGroup(detections, groups)
61
 
62
+ // Detect hardware capability: try the in-browser model first, and fall back
63
+ // to the server-side detector when the device can't load / run it locally.
64
+ const initEngine = () => {
65
  setModelError('')
66
+ setEngine('checking')
67
+ // probe the server in parallel so a fallback is ready if local fails
68
+ isServerDetectAvailable().then(setServerAvailable).catch(() => setServerAvailable(false))
69
+
70
  loadModel(setStatus)
71
+ .then(() => {
72
+ setEngine('local')
 
73
  setStatus('')
74
  })
75
+ .catch(async (err: unknown) => {
76
+ const message = err instanceof Error ? err.message : String(err)
77
+ setStatus('')
78
+ // local failed — see if the server fallback can take over
79
+ const ok = await isServerDetectAvailable()
80
+ setServerAvailable(ok)
81
+ if (ok) {
82
+ setEngine('server')
83
+ setModelError('')
84
+ } else {
85
+ setEngine('none')
86
+ setModelError(message)
87
+ }
88
+ })
89
  }
90
 
91
  useEffect(() => {
92
+ initEngine()
93
  // eslint-disable-next-line react-hooks/exhaustive-deps
94
  }, [])
95
 
 
102
  img.onload = () => {
103
  setImage(img)
104
  setImageSrc(url)
105
+ setImageFile(file)
106
  setImageDims({ w: img.naturalWidth, h: img.naturalHeight })
107
  setDetections([])
108
  setGroups([])
 
112
  }
113
 
114
  // -------------------------------------------------------------------------
115
+ // counting — routes to local (in-browser) or server-side detection
116
  // -------------------------------------------------------------------------
117
+ const detectLocal = (img: HTMLImageElement) =>
118
+ runDetection(img, {
119
+ useTiling,
120
+ enhanceImage: false,
121
+ filterOutliers,
122
+ autoTile: !useTiling,
123
+ onProgress: setStatus,
124
+ })
125
+
126
+ const detectServer = (file: File) =>
127
+ serverDetect(file, { useTiling, filterOutliers, onProgress: setStatus })
128
+
129
  const runCount = async () => {
130
  if (!image) return
131
  setBusy(true)
132
  setStatus(t(lang, 'processing'))
133
  navigate('counting')
134
  try {
135
+ let dets: Detection[]
136
+
137
+ if (engine === 'server') {
138
+ if (!imageFile) throw new Error('Image unavailable for server detection')
139
+ dets = await detectServer(imageFile)
140
+ } else {
141
+ // local engine — but if it fails at runtime, transparently fall back
142
+ try {
143
+ dets = await detectLocal(image)
144
+ } catch (localErr) {
145
+ if (serverAvailable && imageFile) {
146
+ setStatus(t(lang, 'fallbackServer'))
147
+ dets = await detectServer(imageFile)
148
+ setEngine('server')
149
+ } else {
150
+ throw localErr
151
+ }
152
+ }
153
+ }
154
+
155
  const clustered = assignDiameterGroups(dets, groupCount, lang)
156
  setDetections(clustered.detections)
157
  setGroups(clustered.groups)
158
+ setStatus(`Done (${engine === 'server' ? 'server' : getActiveBackend()})`)
159
  navigate('results')
160
  } catch (err) {
161
+ setStatus(err instanceof Error ? err.message : String(err))
162
  navigate('preview')
163
  } finally {
164
  setBusy(false)
 
181
  setGroups([])
182
  setImage(null)
183
  setImageSrc('')
184
+ setImageFile(null)
185
  }
186
 
187
  // -------------------------------------------------------------------------
 
205
  <img src="/icon.svg" alt="" className="h-7 w-7 rounded-xl" />
206
  <span
207
  className={`absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full border-2 border-[var(--bg)] transition-colors duration-700 ${
208
+ engine === 'local'
209
+ ? 'bg-emerald-400'
210
+ : engine === 'server'
211
+ ? 'bg-sky-400'
212
+ : engine === 'none'
213
+ ? 'bg-red-400'
214
+ : 'animate-pulse bg-amber-400'
215
  }`}
216
  />
217
  </div>
 
254
  {step === 'capture' && (
255
  <StepCapture
256
  lang={lang}
257
+ engine={engine}
258
  modelError={modelError}
259
+ onRetryModel={initEngine}
260
  onCamera={() => cameraRef.current?.click()}
261
  onGallery={() => fileRef.current?.click()}
262
  />
 
268
  imageSrc={imageSrc}
269
  imageDims={imageDims}
270
  busy={busy}
271
+ modelReady={engine === 'local' || engine === 'server'}
272
  groupCount={groupCount}
273
  useTiling={useTiling}
274
  filterOutliers={filterOutliers}
frontend/src/components/StepCapture.tsx CHANGED
@@ -1,18 +1,21 @@
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 */}
@@ -46,12 +49,16 @@ export function StepCapture({ lang, modelReady, modelError, onRetryModel, onCame
46
  >
47
  <img src="/icon.svg" alt="" className="h-18 w-18" style={{ width: 72, height: 72 }} />
48
 
49
- {/* Model-ready dot */}
50
  <span
51
  className={`absolute -right-1.5 -top-1.5 h-5 w-5 rounded-full border-[3px] border-[var(--bg)] transition-all duration-700 ${
52
- modelReady
53
  ? 'bg-emerald-400 shadow-[0_0_12px_rgba(52,211,153,0.8)]'
54
- : 'animate-pulse bg-amber-400 shadow-[0_0_10px_rgba(251,191,36,0.7)]'
 
 
 
 
55
  }`}
56
  />
57
  </div>
@@ -66,7 +73,7 @@ export function StepCapture({ lang, modelReady, modelError, onRetryModel, onCame
66
  </p>
67
  </div>
68
 
69
- {/* Model status badge */}
70
  {hasError ? (
71
  <button
72
  type="button"
@@ -76,20 +83,23 @@ export function StepCapture({ lang, modelReady, modelError, onRetryModel, onCame
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>
 
1
+ import { AlertTriangle, Camera, Cloud, ImagePlus, RotateCcw } from 'lucide-react'
2
  import { t } from '../lib/i18n'
3
  import type { Lang } from '../lib/types'
4
 
5
+ type Engine = 'checking' | 'local' | 'server' | 'none'
6
+
7
  interface Props {
8
  lang: Lang
9
+ engine: Engine
10
  modelError?: string
11
  onRetryModel?: () => void
12
  onCamera: () => void
13
  onGallery: () => void
14
  }
15
 
16
+ export function StepCapture({ lang, engine, modelError, onRetryModel, onCamera, onGallery }: Props) {
17
+ const hasError = engine === 'none' || Boolean(modelError)
18
+ const ready = engine === 'local' || engine === 'server'
19
  return (
20
  <div className="relative flex flex-1 flex-col overflow-hidden">
21
  {/* Background ambient glow */}
 
49
  >
50
  <img src="/icon.svg" alt="" className="h-18 w-18" style={{ width: 72, height: 72 }} />
51
 
52
+ {/* Engine-ready dot */}
53
  <span
54
  className={`absolute -right-1.5 -top-1.5 h-5 w-5 rounded-full border-[3px] border-[var(--bg)] transition-all duration-700 ${
55
+ engine === 'local'
56
  ? 'bg-emerald-400 shadow-[0_0_12px_rgba(52,211,153,0.8)]'
57
+ : engine === 'server'
58
+ ? 'bg-sky-400 shadow-[0_0_12px_rgba(56,189,248,0.8)]'
59
+ : engine === 'none'
60
+ ? 'bg-red-400 shadow-[0_0_10px_rgba(248,113,113,0.7)]'
61
+ : 'animate-pulse bg-amber-400 shadow-[0_0_10px_rgba(251,191,36,0.7)]'
62
  }`}
63
  />
64
  </div>
 
73
  </p>
74
  </div>
75
 
76
+ {/* Engine status badge */}
77
  {hasError ? (
78
  <button
79
  type="button"
 
83
  <RotateCcw size={12} />
84
  {t(lang, 'retry')}
85
  </button>
86
+ ) : engine === 'server' ? (
87
+ <div className="flex items-center gap-1.5 rounded-full bg-sky-500/15 px-3 py-1 text-xs font-medium text-sky-300">
88
+ <Cloud size={12} />
89
+ {t(lang, 'cloudMode')}
90
+ </div>
91
  ) : (
92
  <div
93
  className={`flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium transition-colors duration-500 ${
94
+ ready ? 'bg-emerald-500/15 text-emerald-300' : 'bg-amber-500/15 text-amber-300'
 
 
95
  }`}
96
  >
97
  <span
98
  className={`h-1.5 w-1.5 rounded-full ${
99
+ ready ? 'bg-emerald-400' : 'animate-pulse bg-amber-400'
100
  }`}
101
  />
102
+ {ready ? t(lang, 'modelReady') : t(lang, 'loadingModel')}
103
  </div>
104
  )}
105
  </div>
frontend/src/lib/i18n.ts CHANGED
@@ -23,6 +23,8 @@ const messages = {
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',
@@ -73,6 +75,8 @@ const messages = {
73
  modelReady: 'โมเดลพร้อมใช้งาน',
74
  modelErrorTitle: 'โหลดโมเดล AI ไม่สำเร็จ',
75
  retry: 'ลองใหม่',
 
 
76
  processing: 'กำลังประมวลผล...',
77
  pleaseWait: 'รูปขนาดใหญ่อาจใช้เวลาสักครู่',
78
  total: 'จำนวนท่อรวม',
 
23
  modelReady: 'Model ready',
24
  modelErrorTitle: 'Could not load the AI model',
25
  retry: 'Retry',
26
+ cloudMode: 'Cloud mode',
27
+ fallbackServer: 'Switching to server…',
28
  processing: 'Processing...',
29
  pleaseWait: 'This may take a moment on large photos.',
30
  total: 'Total pipes',
 
75
  modelReady: 'โมเดลพร้อมใช้งาน',
76
  modelErrorTitle: 'โหลดโมเดล AI ไม่สำเร็จ',
77
  retry: 'ลองใหม่',
78
+ cloudMode: 'โหมดเซิร์ฟเวอร์',
79
+ fallbackServer: 'กำลังสลับไปเซิร์ฟเวอร์…',
80
  processing: 'กำลังประมวลผล...',
81
  pleaseWait: 'รูปขนาดใหญ่อาจใช้เวลาสักครู่',
82
  total: 'จำนวนท่อรวม',
frontend/src/lib/serverDetect.ts ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Server-side detection fallback.
3
+ *
4
+ * When a device cannot load / run the in-browser ONNX model (old Android,
5
+ * no WebGPU, low memory, blocked WASM, etc.) we POST the original photo to the
6
+ * FastAPI `/detect` endpoint which runs the same model on the server CPU.
7
+ */
8
+ import type { Detection } from './types'
9
+
10
+ interface ServerDetectResponse {
11
+ detections: Array<{ xmin: number; ymin: number; xmax: number; ymax: number; confidence: number }>
12
+ count: number
13
+ width: number
14
+ height: number
15
+ ms: number
16
+ model: string
17
+ mode: string
18
+ backend: string
19
+ }
20
+
21
+ let serverBackend = 'server'
22
+
23
+ export function getServerBackend(): string {
24
+ return serverBackend
25
+ }
26
+
27
+ /**
28
+ * Probe whether the server-side detection fallback is reachable and ready.
29
+ * Returns false on any network error (e.g. installed PWA running offline).
30
+ */
31
+ export async function isServerDetectAvailable(timeoutMs = 4000): Promise<boolean> {
32
+ try {
33
+ const controller = new AbortController()
34
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
35
+ const res = await fetch('/health', { signal: controller.signal })
36
+ clearTimeout(timer)
37
+ if (!res.ok) return false
38
+ const data = (await res.json()) as { server_detect?: boolean }
39
+ return Boolean(data.server_detect)
40
+ } catch {
41
+ return false
42
+ }
43
+ }
44
+
45
+ export async function serverDetect(
46
+ file: Blob,
47
+ options?: {
48
+ useTiling?: boolean
49
+ filterOutliers?: boolean
50
+ onProgress?: (msg: string) => void
51
+ },
52
+ ): Promise<Detection[]> {
53
+ options?.onProgress?.('Uploading to server...')
54
+
55
+ const form = new FormData()
56
+ form.append('file', file, 'photo.jpg')
57
+ form.append('tiling', String(options?.useTiling ?? false))
58
+ form.append('auto_tile', String(options?.useTiling ? false : true))
59
+ form.append('outliers', String(options?.filterOutliers ?? false))
60
+
61
+ options?.onProgress?.('Counting on server...')
62
+ const res = await fetch('/detect', { method: 'POST', body: form })
63
+ if (!res.ok) {
64
+ let detail = `Server detection failed (${res.status})`
65
+ try {
66
+ const err = (await res.json()) as { detail?: string }
67
+ if (err.detail) detail = err.detail
68
+ } catch {
69
+ /* ignore parse error */
70
+ }
71
+ throw new Error(detail)
72
+ }
73
+
74
+ const data = (await res.json()) as ServerDetectResponse
75
+ serverBackend = data.backend ?? 'server'
76
+ options?.onProgress?.(`Detected ${data.count} pipes (${data.ms}ms, ${serverBackend})`)
77
+
78
+ return data.detections.map((d, idx) => ({
79
+ xmin: d.xmin,
80
+ ymin: d.ymin,
81
+ xmax: d.xmax,
82
+ ymax: d.ymax,
83
+ confidence: d.confidence,
84
+ id: `srv-${idx}`,
85
+ groupId: 0,
86
+ }))
87
+ }
main.py CHANGED
@@ -1,14 +1,19 @@
1
  from pathlib import Path
2
 
3
- from fastapi import FastAPI, HTTPException
4
  from fastapi.middleware.cors import CORSMiddleware
5
  from fastapi.responses import FileResponse, JSONResponse
6
  from starlette.middleware.base import BaseHTTPMiddleware
7
  from starlette.requests import Request
8
 
 
 
9
  APP_VERSION = "1.0.0"
10
  STATIC_PATH = Path(__file__).resolve().parent / "static"
11
 
 
 
 
12
 
13
  class CrossOriginIsolationMiddleware(BaseHTTPMiddleware):
14
  async def dispatch(self, request: Request, call_next):
@@ -42,10 +47,44 @@ async def health_check():
42
  "version": APP_VERSION,
43
  "mode": "static-pwa",
44
  "model_present": model_path.is_file(),
 
 
45
  }
46
  )
47
 
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  @app.get("/{filename:path}")
50
  async def serve_file(filename: str):
51
  if not filename:
 
1
  from pathlib import Path
2
 
3
+ from fastapi import FastAPI, File, Form, HTTPException, UploadFile
4
  from fastapi.middleware.cors import CORSMiddleware
5
  from fastapi.responses import FileResponse, JSONResponse
6
  from starlette.middleware.base import BaseHTTPMiddleware
7
  from starlette.requests import Request
8
 
9
+ import detect
10
+
11
  APP_VERSION = "1.0.0"
12
  STATIC_PATH = Path(__file__).resolve().parent / "static"
13
 
14
+ # 25 MB upload cap — enough for high-res phone photos, blocks abuse.
15
+ MAX_UPLOAD_BYTES = 25 * 1024 * 1024
16
+
17
 
18
  class CrossOriginIsolationMiddleware(BaseHTTPMiddleware):
19
  async def dispatch(self, request: Request, call_next):
 
47
  "version": APP_VERSION,
48
  "mode": "static-pwa",
49
  "model_present": model_path.is_file(),
50
+ # tells the client whether the server-side detection fallback is usable
51
+ "server_detect": detect.is_available(),
52
  }
53
  )
54
 
55
 
56
+ @app.post("/detect")
57
+ async def detect_endpoint(
58
+ file: UploadFile = File(...),
59
+ tiling: bool = Form(False),
60
+ auto_tile: bool = Form(True),
61
+ outliers: bool = Form(False),
62
+ ):
63
+ """Server-side detection fallback for devices that can't run the model locally."""
64
+ if not detect.is_available():
65
+ raise HTTPException(status_code=503, detail="Server-side detection is not available")
66
+
67
+ data = await file.read()
68
+ if not data:
69
+ raise HTTPException(status_code=400, detail="Empty upload")
70
+ if len(data) > MAX_UPLOAD_BYTES:
71
+ raise HTTPException(status_code=413, detail="Image too large")
72
+
73
+ try:
74
+ result = detect.detect_bytes(
75
+ data,
76
+ use_tiling=True if tiling else None,
77
+ auto_tile=auto_tile,
78
+ filter_outliers_flag=outliers,
79
+ )
80
+ except ValueError as exc:
81
+ raise HTTPException(status_code=400, detail=str(exc))
82
+ except Exception as exc: # noqa: BLE001 - surface a clean 500 to the client
83
+ raise HTTPException(status_code=500, detail=f"Detection failed: {exc}")
84
+
85
+ return JSONResponse(result)
86
+
87
+
88
  @app.get("/{filename:path}")
89
  async def serve_file(filename: str):
90
  if not filename:
requirements-server.txt CHANGED
@@ -1,4 +1,9 @@
1
- # Slim server requirements (no torch)
 
 
2
  fastapi>=0.115.0
3
  uvicorn>=0.32.0
4
  python-multipart>=0.0.9
 
 
 
 
1
+ # Slim server requirements (no torch).
2
+ # Includes a lightweight ONNX Runtime CPU stack so the server can act as a
3
+ # detection fallback when a client device cannot run the in-browser model.
4
  fastapi>=0.115.0
5
  uvicorn>=0.32.0
6
  python-multipart>=0.0.9
7
+ onnxruntime>=1.17.0
8
+ numpy>=1.24.0
9
+ opencv-python-headless>=4.8.0