Khunndev Cursor commited on
Commit
238d8e3
·
1 Parent(s): bdf846b

Add crop step to define detection area before server counting.

Browse files
frontend/src/App.tsx CHANGED
@@ -6,20 +6,22 @@ import { getActiveBackend, isLowMemoryDevice, loadModel, runDetection } from './
6
  import { loadInferenceMode, saveInferenceMode } from './lib/inferenceSettings'
7
  import { getServerBackend, probeServerDetect, serverDetect } from './lib/serverDetect'
8
  import { t } from './lib/i18n'
 
9
  import type { Detection, DiameterGroup, InferenceMode, Lang } from './lib/types'
10
  import { StepCapture } from './components/StepCapture'
 
11
  import { StepCounting } from './components/StepCounting'
12
  import { StepPreview } from './components/StepPreview'
13
  import { StepResults } from './components/StepResults'
14
  import { SettingsDrawer } from './components/SettingsDrawer'
15
  import { CreditFooter } from './components/CreditFooter'
16
 
17
- type Step = 'capture' | 'preview' | 'counting' | 'results'
18
 
19
  // Runtime capability — which engine is actually ready right now.
20
  type Engine = 'checking' | 'local' | 'server' | 'none'
21
 
22
- const STEPS: Step[] = ['capture', 'preview', 'counting', 'results']
23
 
24
  export default function App() {
25
  const [step, setStep] = useState<Step>('capture')
@@ -31,7 +33,10 @@ export default function App() {
31
  setStep(next)
32
  }
33
 
34
- // image
 
 
 
35
  const [image, setImage] = useState<HTMLImageElement | null>(null)
36
  const [imageSrc, setImageSrc] = useState('')
37
  const [imageFile, setImageFile] = useState<File | null>(null)
@@ -130,6 +135,20 @@ export default function App() {
130
  setInferenceMode(mode)
131
  }
132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  // -------------------------------------------------------------------------
134
  // file / camera
135
  // -------------------------------------------------------------------------
@@ -137,17 +156,39 @@ export default function App() {
137
  const url = URL.createObjectURL(file)
138
  const img = new Image()
139
  img.onload = () => {
140
- setImage(img)
141
- setImageSrc(url)
142
- setImageFile(file)
143
- setImageDims({ w: img.naturalWidth, h: img.naturalHeight })
 
 
 
 
 
144
  setDetections([])
145
  setGroups([])
146
- navigate('preview')
147
  }
148
  img.src = url
149
  }
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  // -------------------------------------------------------------------------
152
  // counting — follows the user's inference mode setting
153
  // -------------------------------------------------------------------------
@@ -240,6 +281,11 @@ export default function App() {
240
  navigate('capture')
241
  setDetections([])
242
  setGroups([])
 
 
 
 
 
243
  setImage(null)
244
  setImageSrc('')
245
  setImageFile(null)
@@ -320,6 +366,18 @@ export default function App() {
320
  />
321
  )}
322
 
 
 
 
 
 
 
 
 
 
 
 
 
323
  {step === 'preview' && image && (
324
  <StepPreview
325
  lang={lang}
@@ -327,7 +385,7 @@ export default function App() {
327
  imageDims={imageDims}
328
  busy={busy}
329
  modelReady={canCount}
330
- onBack={resetToCapture}
331
  onRetake={() => cameraRef.current?.click()}
332
  onGallery={() => fileRef.current?.click()}
333
  onCount={runCount}
@@ -347,7 +405,7 @@ export default function App() {
347
  counts={counts}
348
  onUpdate={setDetections}
349
  onExpectedChange={handleExpectedChange}
350
- onRecount={() => navigate('preview')}
351
  onNewPhoto={resetToCapture}
352
  />
353
  )}
 
6
  import { loadInferenceMode, saveInferenceMode } from './lib/inferenceSettings'
7
  import { getServerBackend, probeServerDetect, serverDetect } from './lib/serverDetect'
8
  import { t } from './lib/i18n'
9
+ import { applyCrop, type CropRect } from './lib/cropImage'
10
  import type { Detection, DiameterGroup, InferenceMode, Lang } from './lib/types'
11
  import { StepCapture } from './components/StepCapture'
12
+ import { StepCrop } from './components/StepCrop'
13
  import { StepCounting } from './components/StepCounting'
14
  import { StepPreview } from './components/StepPreview'
15
  import { StepResults } from './components/StepResults'
16
  import { SettingsDrawer } from './components/SettingsDrawer'
17
  import { CreditFooter } from './components/CreditFooter'
18
 
19
+ type Step = 'capture' | 'crop' | 'preview' | 'counting' | 'results'
20
 
21
  // Runtime capability — which engine is actually ready right now.
22
  type Engine = 'checking' | 'local' | 'server' | 'none'
23
 
24
+ const STEPS: Step[] = ['capture', 'crop', 'preview', 'counting', 'results']
25
 
26
  export default function App() {
27
  const [step, setStep] = useState<Step>('capture')
 
33
  setStep(next)
34
  }
35
 
36
+ // image — source = original upload; image = cropped area used for detection
37
+ const [sourceImage, setSourceImage] = useState<HTMLImageElement | null>(null)
38
+ const [sourceSrc, setSourceSrc] = useState('')
39
+ const [sourceFile, setSourceFile] = useState<File | null>(null)
40
  const [image, setImage] = useState<HTMLImageElement | null>(null)
41
  const [imageSrc, setImageSrc] = useState('')
42
  const [imageFile, setImageFile] = useState<File | null>(null)
 
135
  setInferenceMode(mode)
136
  }
137
 
138
+ const revokeIfBlob = (url: string) => {
139
+ if (url.startsWith('blob:')) URL.revokeObjectURL(url)
140
+ }
141
+
142
+ const setWorkingImage = (img: HTMLImageElement, file: File, url: string) => {
143
+ if (imageSrc && imageSrc !== url) revokeIfBlob(imageSrc)
144
+ setImage(img)
145
+ setImageFile(file)
146
+ setImageSrc(url)
147
+ setImageDims({ w: img.naturalWidth, h: img.naturalHeight })
148
+ setDetections([])
149
+ setGroups([])
150
+ }
151
+
152
  // -------------------------------------------------------------------------
153
  // file / camera
154
  // -------------------------------------------------------------------------
 
156
  const url = URL.createObjectURL(file)
157
  const img = new Image()
158
  img.onload = () => {
159
+ revokeIfBlob(sourceSrc)
160
+ revokeIfBlob(imageSrc)
161
+ setSourceImage(img)
162
+ setSourceSrc(url)
163
+ setSourceFile(file)
164
+ setImage(null)
165
+ setImageFile(null)
166
+ setImageSrc('')
167
+ setImageDims({ w: 0, h: 0 })
168
  setDetections([])
169
  setGroups([])
170
+ navigate('crop')
171
  }
172
  img.src = url
173
  }
174
 
175
+ const handleCropConfirm = async (crop: CropRect) => {
176
+ if (!sourceImage || !sourceFile) return
177
+ try {
178
+ const cropped = await applyCrop(sourceImage, crop)
179
+ setWorkingImage(cropped.image, cropped.file, cropped.url)
180
+ navigate('preview')
181
+ } catch (err) {
182
+ setStatus(err instanceof Error ? err.message : String(err))
183
+ }
184
+ }
185
+
186
+ const handleUseFullImage = () => {
187
+ if (!sourceImage || !sourceFile || !sourceSrc) return
188
+ setWorkingImage(sourceImage, sourceFile, sourceSrc)
189
+ navigate('preview')
190
+ }
191
+
192
  // -------------------------------------------------------------------------
193
  // counting — follows the user's inference mode setting
194
  // -------------------------------------------------------------------------
 
281
  navigate('capture')
282
  setDetections([])
283
  setGroups([])
284
+ revokeIfBlob(sourceSrc)
285
+ revokeIfBlob(imageSrc)
286
+ setSourceImage(null)
287
+ setSourceSrc('')
288
+ setSourceFile(null)
289
  setImage(null)
290
  setImageSrc('')
291
  setImageFile(null)
 
366
  />
367
  )}
368
 
369
+ {step === 'crop' && sourceImage && (
370
+ <StepCrop
371
+ lang={lang}
372
+ imageSrc={sourceSrc}
373
+ naturalW={sourceImage.naturalWidth}
374
+ naturalH={sourceImage.naturalHeight}
375
+ onBack={resetToCapture}
376
+ onConfirm={(crop) => void handleCropConfirm(crop)}
377
+ onUseFull={handleUseFullImage}
378
+ />
379
+ )}
380
+
381
  {step === 'preview' && image && (
382
  <StepPreview
383
  lang={lang}
 
385
  imageDims={imageDims}
386
  busy={busy}
387
  modelReady={canCount}
388
+ onBack={() => navigate('crop')}
389
  onRetake={() => cameraRef.current?.click()}
390
  onGallery={() => fileRef.current?.click()}
391
  onCount={runCount}
 
405
  counts={counts}
406
  onUpdate={setDetections}
407
  onExpectedChange={handleExpectedChange}
408
+ onRecount={() => navigate('crop')}
409
  onNewPhoto={resetToCapture}
410
  />
411
  )}
frontend/src/components/StepCrop.tsx ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useCallback, useEffect, useRef, useState } from 'react'
2
+ import { ChevronLeft, Crop, Maximize2 } from 'lucide-react'
3
+ import {
4
+ clampCropRect,
5
+ computeDisplayLayout,
6
+ cropToDisplay,
7
+ defaultCropRect,
8
+ type CropRect,
9
+ type DisplayLayout,
10
+ } from '../lib/cropImage'
11
+ import { t } from '../lib/i18n'
12
+ import type { Lang } from '../lib/types'
13
+
14
+ type Handle = 'move' | 'nw' | 'ne' | 'sw' | 'se'
15
+
16
+ interface Props {
17
+ lang: Lang
18
+ imageSrc: string
19
+ naturalW: number
20
+ naturalH: number
21
+ onBack: () => void
22
+ onConfirm: (crop: CropRect) => void
23
+ onUseFull: () => void
24
+ }
25
+
26
+ export function StepCrop({
27
+ lang,
28
+ imageSrc,
29
+ naturalW,
30
+ naturalH,
31
+ onBack,
32
+ onConfirm,
33
+ onUseFull,
34
+ }: Props) {
35
+ const containerRef = useRef<HTMLDivElement>(null)
36
+ const [layout, setLayout] = useState<DisplayLayout | null>(null)
37
+ const [crop, setCrop] = useState<CropRect>(() => defaultCropRect(naturalW, naturalH))
38
+ const dragRef = useRef<{
39
+ handle: Handle
40
+ startX: number
41
+ startY: number
42
+ startCrop: CropRect
43
+ } | null>(null)
44
+ const layoutRef = useRef(layout)
45
+ layoutRef.current = layout
46
+ const naturalRef = useRef({ w: naturalW, h: naturalH })
47
+ naturalRef.current = { w: naturalW, h: naturalH }
48
+
49
+ const measure = useCallback(() => {
50
+ const el = containerRef.current
51
+ if (!el) return
52
+ const next = computeDisplayLayout(el.clientWidth, el.clientHeight, naturalW, naturalH)
53
+ if (next.width > 0 && next.height > 0) setLayout(next)
54
+ }, [naturalW, naturalH])
55
+
56
+ useEffect(() => {
57
+ measure()
58
+ const el = containerRef.current
59
+ if (!el) return
60
+ const ro = new ResizeObserver(measure)
61
+ ro.observe(el)
62
+ return () => ro.disconnect()
63
+ }, [measure])
64
+
65
+ useEffect(() => {
66
+ setCrop(defaultCropRect(naturalW, naturalH))
67
+ }, [naturalW, naturalH, imageSrc])
68
+
69
+ const displayCrop = layout ? cropToDisplay(crop, layout, naturalW, naturalH) : null
70
+
71
+ const startDrag = (handle: Handle, clientX: number, clientY: number) => {
72
+ dragRef.current = { handle, startX: clientX, startY: clientY, startCrop: crop }
73
+ }
74
+
75
+ const onPointerMove = useCallback((clientX: number, clientY: number) => {
76
+ const drag = dragRef.current
77
+ const layoutNow = layoutRef.current
78
+ if (!drag || !layoutNow) return
79
+
80
+ const { w: naturalWNow, h: naturalHNow } = naturalRef.current
81
+ const dx = ((clientX - drag.startX) / layoutNow.width) * naturalWNow
82
+ const dy = ((clientY - drag.startY) / layoutNow.height) * naturalHNow
83
+ const s = drag.startCrop
84
+ let next: CropRect
85
+
86
+ switch (drag.handle) {
87
+ case 'move':
88
+ next = { ...s, x: s.x + dx, y: s.y + dy }
89
+ break
90
+ case 'nw':
91
+ next = {
92
+ x: s.x + dx,
93
+ y: s.y + dy,
94
+ width: s.width - dx,
95
+ height: s.height - dy,
96
+ }
97
+ break
98
+ case 'ne':
99
+ next = {
100
+ x: s.x,
101
+ y: s.y + dy,
102
+ width: s.width + dx,
103
+ height: s.height - dy,
104
+ }
105
+ break
106
+ case 'sw':
107
+ next = {
108
+ x: s.x + dx,
109
+ y: s.y,
110
+ width: s.width - dx,
111
+ height: s.height + dy,
112
+ }
113
+ break
114
+ case 'se':
115
+ next = {
116
+ x: s.x,
117
+ y: s.y,
118
+ width: s.width + dx,
119
+ height: s.height + dy,
120
+ }
121
+ break
122
+ }
123
+
124
+ setCrop(clampCropRect(next, naturalWNow, naturalHNow))
125
+ }, [])
126
+
127
+ const endDrag = () => {
128
+ dragRef.current = null
129
+ }
130
+
131
+ useEffect(() => {
132
+ const onMove = (e: PointerEvent) => onPointerMove(e.clientX, e.clientY)
133
+ const onUp = () => endDrag()
134
+ window.addEventListener('pointermove', onMove)
135
+ window.addEventListener('pointerup', onUp)
136
+ window.addEventListener('pointercancel', onUp)
137
+ return () => {
138
+ window.removeEventListener('pointermove', onMove)
139
+ window.removeEventListener('pointerup', onUp)
140
+ window.removeEventListener('pointercancel', onUp)
141
+ }
142
+ }, [onPointerMove])
143
+
144
+ const handleCorner = (corner: Exclude<Handle, 'move'>) => (
145
+ e: React.PointerEvent<HTMLDivElement>,
146
+ ) => {
147
+ e.stopPropagation()
148
+ e.currentTarget.setPointerCapture(e.pointerId)
149
+ startDrag(corner, e.clientX, e.clientY)
150
+ }
151
+
152
+ return (
153
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-[var(--bg)]">
154
+ <div className="flex items-center justify-between px-4 py-2.5">
155
+ <button type="button" className="ct-btn-ghost flex h-9 items-center gap-1 px-3 text-sm" onClick={onBack}>
156
+ <ChevronLeft size={16} strokeWidth={2.5} />
157
+ {t(lang, 'previewBack')}
158
+ </button>
159
+ <p className="text-sm font-semibold text-[var(--text)]">{t(lang, 'cropTitle')}</p>
160
+ <div className="w-16" />
161
+ </div>
162
+
163
+ <p className="px-4 pb-2 text-center text-xs text-[var(--text-dim)]">{t(lang, 'cropHint')}</p>
164
+
165
+ <div
166
+ ref={containerRef}
167
+ className="relative mx-4 min-h-0 flex-1 overflow-hidden rounded-2xl border border-[var(--hairline)] bg-black shadow-[var(--shadow-md)]"
168
+ >
169
+ <img src={imageSrc} alt="" className="absolute inset-0 h-full w-full object-contain" draggable={false} />
170
+
171
+ {displayCrop && (
172
+ <div className="absolute inset-0 touch-none">
173
+ <div
174
+ className="absolute bg-black/55"
175
+ style={{ left: 0, top: 0, right: 0, height: displayCrop.y }}
176
+ />
177
+ <div
178
+ className="absolute bg-black/55"
179
+ style={{
180
+ left: 0,
181
+ top: displayCrop.y,
182
+ width: displayCrop.x,
183
+ height: displayCrop.height,
184
+ }}
185
+ />
186
+ <div
187
+ className="absolute bg-black/55"
188
+ style={{
189
+ left: displayCrop.x + displayCrop.width,
190
+ top: displayCrop.y,
191
+ right: 0,
192
+ height: displayCrop.height,
193
+ }}
194
+ />
195
+ <div
196
+ className="absolute bg-black/55"
197
+ style={{
198
+ left: 0,
199
+ top: displayCrop.y + displayCrop.height,
200
+ right: 0,
201
+ bottom: 0,
202
+ }}
203
+ />
204
+
205
+ <div
206
+ className="absolute cursor-move border-2 border-[var(--brand)]"
207
+ style={{
208
+ left: displayCrop.x,
209
+ top: displayCrop.y,
210
+ width: displayCrop.width,
211
+ height: displayCrop.height,
212
+ boxShadow: '0 0 0 1px rgba(255,255,255,0.35) inset',
213
+ }}
214
+ onPointerDown={(e) => {
215
+ e.currentTarget.setPointerCapture(e.pointerId)
216
+ startDrag('move', e.clientX, e.clientY)
217
+ }}
218
+ >
219
+ <div className="pointer-events-none absolute inset-0 grid grid-cols-3 grid-rows-3 opacity-40">
220
+ {Array.from({ length: 9 }).map((_, i) => (
221
+ <div key={i} className="border border-white/50" />
222
+ ))}
223
+ </div>
224
+
225
+ {(['nw', 'ne', 'sw', 'se'] as const).map((corner) => {
226
+ const pos =
227
+ corner === 'nw'
228
+ ? 'left-0 top-0 -translate-x-1/2 -translate-y-1/2'
229
+ : corner === 'ne'
230
+ ? 'right-0 top-0 translate-x-1/2 -translate-y-1/2'
231
+ : corner === 'sw'
232
+ ? 'left-0 bottom-0 -translate-x-1/2 translate-y-1/2'
233
+ : 'right-0 bottom-0 translate-x-1/2 translate-y-1/2'
234
+ return (
235
+ <div
236
+ key={corner}
237
+ className={`absolute h-5 w-5 rounded-full border-2 border-white bg-[var(--brand)] shadow ${pos}`}
238
+ onPointerDown={handleCorner(corner)}
239
+ />
240
+ )
241
+ })}
242
+ </div>
243
+ </div>
244
+ )}
245
+ </div>
246
+
247
+ <p className="mt-2 text-center text-[11px] tabular-nums text-[var(--text-faint)]">
248
+ {Math.round(crop.width)} × {Math.round(crop.height)}
249
+ </p>
250
+
251
+ <div
252
+ className="mt-3 shrink-0 space-y-2 border-t border-[var(--hairline)] bg-[var(--header-bg)] px-4 pt-3"
253
+ style={{ paddingBottom: 'max(1rem, env(safe-area-inset-bottom))' }}
254
+ >
255
+ <button
256
+ type="button"
257
+ className="ct-btn-secondary flex w-full items-center justify-center gap-2"
258
+ onClick={onUseFull}
259
+ >
260
+ <Maximize2 size={18} />
261
+ {t(lang, 'cropUseFull')}
262
+ </button>
263
+ <button
264
+ type="button"
265
+ className="ct-btn-primary flex w-full items-center justify-center gap-2"
266
+ onClick={() => onConfirm(clampCropRect(crop, naturalW, naturalH))}
267
+ >
268
+ <Crop size={18} />
269
+ {t(lang, 'cropContinue')}
270
+ </button>
271
+ </div>
272
+ </div>
273
+ )
274
+ }
frontend/src/lib/cropImage.ts ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Crop region in natural image pixels. */
2
+ export interface CropRect {
3
+ x: number
4
+ y: number
5
+ width: number
6
+ height: number
7
+ }
8
+
9
+ export interface DisplayLayout {
10
+ offsetX: number
11
+ offsetY: number
12
+ width: number
13
+ height: number
14
+ }
15
+
16
+ const MIN_CROP_PX = 48
17
+
18
+ export function clampCropRect(
19
+ crop: CropRect,
20
+ naturalW: number,
21
+ naturalH: number,
22
+ ): CropRect {
23
+ const minW = Math.min(MIN_CROP_PX, naturalW)
24
+ const minH = Math.min(MIN_CROP_PX, naturalH)
25
+ let { x, y, width, height } = crop
26
+
27
+ width = Math.max(minW, Math.min(width, naturalW))
28
+ height = Math.max(minH, Math.min(height, naturalH))
29
+ x = Math.max(0, Math.min(x, naturalW - width))
30
+ y = Math.max(0, Math.min(y, naturalH - height))
31
+
32
+ return { x, y, width, height }
33
+ }
34
+
35
+ export function defaultCropRect(naturalW: number, naturalH: number): CropRect {
36
+ const marginX = naturalW * 0.08
37
+ const marginY = naturalH * 0.08
38
+ return clampCropRect(
39
+ {
40
+ x: marginX,
41
+ y: marginY,
42
+ width: naturalW - marginX * 2,
43
+ height: naturalH - marginY * 2,
44
+ },
45
+ naturalW,
46
+ naturalH,
47
+ )
48
+ }
49
+
50
+ export function fullCropRect(naturalW: number, naturalH: number): CropRect {
51
+ return { x: 0, y: 0, width: naturalW, height: naturalH }
52
+ }
53
+
54
+ /** object-contain layout of an image inside a container. */
55
+ export function computeDisplayLayout(
56
+ containerW: number,
57
+ containerH: number,
58
+ naturalW: number,
59
+ naturalH: number,
60
+ ): DisplayLayout {
61
+ if (containerW <= 0 || containerH <= 0 || naturalW <= 0 || naturalH <= 0) {
62
+ return { offsetX: 0, offsetY: 0, width: 0, height: 0 }
63
+ }
64
+
65
+ const scale = Math.min(containerW / naturalW, containerH / naturalH)
66
+ const width = naturalW * scale
67
+ const height = naturalH * scale
68
+ return {
69
+ offsetX: (containerW - width) / 2,
70
+ offsetY: (containerH - height) / 2,
71
+ width,
72
+ height,
73
+ }
74
+ }
75
+
76
+ export function cropToDisplay(
77
+ crop: CropRect,
78
+ layout: DisplayLayout,
79
+ naturalW: number,
80
+ naturalH: number,
81
+ ) {
82
+ const sx = layout.width / naturalW
83
+ const sy = layout.height / naturalH
84
+ return {
85
+ x: layout.offsetX + crop.x * sx,
86
+ y: layout.offsetY + crop.y * sy,
87
+ width: crop.width * sx,
88
+ height: crop.height * sy,
89
+ }
90
+ }
91
+
92
+ export function displayToCrop(
93
+ display: { x: number; y: number; width: number; height: number },
94
+ layout: DisplayLayout,
95
+ naturalW: number,
96
+ naturalH: number,
97
+ ): CropRect {
98
+ const sx = naturalW / layout.width
99
+ const sy = naturalH / layout.height
100
+ return clampCropRect(
101
+ {
102
+ x: (display.x - layout.offsetX) * sx,
103
+ y: (display.y - layout.offsetY) * sy,
104
+ width: display.width * sx,
105
+ height: display.height * sy,
106
+ },
107
+ naturalW,
108
+ naturalH,
109
+ )
110
+ }
111
+
112
+ export async function applyCrop(
113
+ source: HTMLImageElement,
114
+ crop: CropRect,
115
+ ): Promise<{ image: HTMLImageElement; file: File; url: string }> {
116
+ const rect = clampCropRect(crop, source.naturalWidth, source.naturalHeight)
117
+ const canvas = document.createElement('canvas')
118
+ canvas.width = Math.round(rect.width)
119
+ canvas.height = Math.round(rect.height)
120
+ const ctx = canvas.getContext('2d')
121
+ if (!ctx) throw new Error('Canvas not supported')
122
+
123
+ ctx.drawImage(
124
+ source,
125
+ rect.x,
126
+ rect.y,
127
+ rect.width,
128
+ rect.height,
129
+ 0,
130
+ 0,
131
+ canvas.width,
132
+ canvas.height,
133
+ )
134
+
135
+ const blob = await new Promise<Blob>((resolve, reject) => {
136
+ canvas.toBlob(
137
+ (b) => (b ? resolve(b) : reject(new Error('Failed to encode crop'))),
138
+ 'image/jpeg',
139
+ 0.92,
140
+ )
141
+ })
142
+
143
+ const file = new File([blob], 'crop.jpg', { type: 'image/jpeg' })
144
+ const url = URL.createObjectURL(blob)
145
+ const image = await new Promise<HTMLImageElement>((resolve, reject) => {
146
+ const img = new Image()
147
+ img.onload = () => resolve(img)
148
+ img.onerror = () => reject(new Error('Failed to load cropped image'))
149
+ img.src = url
150
+ })
151
+
152
+ return { image, file, url }
153
+ }
frontend/src/lib/i18n.ts CHANGED
@@ -8,6 +8,10 @@ const messages = {
8
  captureSubtitle: 'Take a photo or choose from gallery',
9
  previewTitle: 'Configure & Count',
10
  previewBack: 'Back',
 
 
 
 
11
  countNow: 'Count Pipes',
12
  retake: 'Retake',
13
  countingTitle: 'Counting pipes…',
@@ -71,6 +75,10 @@ const messages = {
71
  captureSubtitle: 'ถ่ายภาพหรือเลือกจากคลัง',
72
  previewTitle: 'ตั้งค่าและนับ',
73
  previewBack: 'ย้อนกลับ',
 
 
 
 
74
  countNow: 'นับท่อ',
75
  retake: 'ถ่ายใหม่',
76
  countingTitle: 'กำลังนับท่อ…',
 
8
  captureSubtitle: 'Take a photo or choose from gallery',
9
  previewTitle: 'Configure & Count',
10
  previewBack: 'Back',
11
+ cropTitle: 'Select detection area',
12
+ cropHint: 'Drag the box or corners to frame the pipe bundle.',
13
+ cropContinue: 'Use this area',
14
+ cropUseFull: 'Use full image',
15
  countNow: 'Count Pipes',
16
  retake: 'Retake',
17
  countingTitle: 'Counting pipes…',
 
75
  captureSubtitle: 'ถ่ายภาพหรือเลือกจากคลัง',
76
  previewTitle: 'ตั้งค่าและนับ',
77
  previewBack: 'ย้อนกลับ',
78
+ cropTitle: 'เลือกพื้นที่นับ',
79
+ cropHint: 'ลากกรอบหรือมุมเพื่อกำหนดบริเวณมัดท่อ',
80
+ cropContinue: 'ใช้พื้นที่นี้',
81
+ cropUseFull: 'ใช้รูปเต็ม',
82
  countNow: 'นับท่อ',
83
  retake: 'ถ่ายใหม่',
84
  countingTitle: 'กำลังนับท่อ…',