Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 'use client' import { useCallback, useRef, useState } from 'react' import { css } from '../../../../../styled-system/css' import { CameraCapture, type CameraSource } from '@/components/vision/CameraCapture' import { saveBoundarySample } from '@/lib/vision/saveBoundarySample' import type { CalibrationGrid } from '@/types/vision' interface BoundaryDataCaptureProps { /** Called when samples are saved successfully */ onSamplesCollected: () => void } /** Minimum time between auto-captures (ms) - keep low to maximize training data */ const AUTO_CAPTURE_COOLDOWN_MS = 200 /** * Capture training data for the boundary detector model. * * Unlike TrainingDataCapture which slices images into columns for digit classification, * this component captures FULL frames with their marker corner positions. * These samples train a model to detect abacus boundaries without markers. * * CRITICAL: This component AUTO-CAPTURES when all 4 markers are detected. * Marker detection is ephemeral - by the time a user could click a button, * the video frame has changed and markers may be gone. So we capture * immediately when markers are found, with rate limiting to prevent spam. * * The captured data includes: * - The raw video frame (before perspective correction) * - The detected marker corner positions (ground truth for training) */ export function BoundaryDataCapture({ onSamplesCollected }: BoundaryDataCaptureProps) { // Capture state const [isAutoCapturing, setIsAutoCapturing] = useState(false) const [lastCaptureStatus, setLastCaptureStatus] = useState<{ success: boolean message: string timestamp: number } | null>(null) const [captureCount, setCaptureCount] = useState(0) const [isPhoneConnected, setIsPhoneConnected] = useState(false) const [cameraSource, setCameraSource] = useState<CameraSource>('local') const [markersCurrentlyVisible, setMarkersCurrentlyVisible] = useState(false) const captureElementRef = useRef<HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | null>( null ) const lastCaptureTimeRef = useRef<number>(0) const isCapturingRef = useRef(false) // Handle video/image/canvas element from camera const handleCapture = useCallback( (element: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement) => { captureElementRef.current = element }, [] ) /** * Auto-capture when calibration changes (markers detected). * This is called on every frame where markers are found - we rate-limit here. */ const handleCalibrationChange = useCallback( async (calibration: CalibrationGrid | null) => { // Track marker visibility for UI const hasCorners = calibration?.corners != null setMarkersCurrentlyVisible(hasCorners) // Only proceed if we have valid corners and auto-capture is enabled if (!hasCorners || !isAutoCapturing) return // Rate limit - don't capture more than once per cooldown period const now = Date.now() if (now - lastCaptureTimeRef.current < AUTO_CAPTURE_COOLDOWN_MS) return // Prevent concurrent captures if (isCapturingRef.current) return const element = captureElementRef.current if (!element) return // For video, check if it's playing if (element instanceof HTMLVideoElement && element.readyState < 2) return // For image, check if it's loaded if (element instanceof HTMLImageElement && (!element.complete || element.naturalWidth === 0)) return // For canvas, check dimensions if (element instanceof HTMLCanvasElement && (element.width === 0 || element.height === 0)) return // Mark as capturing isCapturingRef.current = true lastCaptureTimeRef.current = now try { // Create a canvas to capture the raw frame const canvas = document.createElement('canvas') let width: number let height: number if (element instanceof HTMLVideoElement) { width = element.videoWidth height = element.videoHeight } else if (element instanceof HTMLCanvasElement) { width = element.width height = element.height } else { width = element.naturalWidth height = element.naturalHeight } canvas.width = width canvas.height = height const ctx = canvas.getContext('2d') if (!ctx) throw new Error('Failed to create canvas context') ctx.drawImage(element, 0, 0) // Convert to base64 PNG (saveBoundarySample handles the data URL prefix) const frameDataUrl = canvas.toDataURL('image/png') // Use shared saveBoundarySample utility // CRITICAL: Use the corners from THIS callback, not stale state const result = await saveBoundarySample({ imageData: frameDataUrl, corners: calibration.corners!, frameWidth: width, frameHeight: height, deviceId: 'explicit-training', }) if (result.success) { setCaptureCount((c) => c + 1) setLastCaptureStatus({ success: true, message: 'Auto-captured frame', timestamp: now, }) onSamplesCollected() } else { throw new Error(result.error || 'Failed to save') } } catch (error) { console.error('[BoundaryDataCapture] Auto-capture error:', error) setLastCaptureStatus({ success: false, message: error instanceof Error ? error.message : 'Capture failed', timestamp: now, }) } finally { isCapturingRef.current = false } }, [isAutoCapturing, onSamplesCollected] ) // Determine if capture is possible const canCapture = cameraSource === 'local' || isPhoneConnected return ( <div data-component="boundary-data-capture" className={css({ p: 3, bg: 'purple.900/20', border: '1px solid', borderColor: 'purple.700/50', borderRadius: 'lg', })} > {/* Header */} <div className={css({ display: 'flex', alignItems: 'center', gap: 2, mb: 3, })} > <span>🎯</span> <span className={css({ fontWeight: 'medium', color: 'purple.300' })}> Capture Boundary Frames </span> {captureCount > 0 && ( <span className={css({ fontSize: 'xs', color: 'green.400', ml: 'auto' })}> +{captureCount} this session </span> )} </div> {/* Camera capture component - no rectified view, we want raw frames */} <CameraCapture initialSource="local" onCapture={handleCapture} onSourceChange={setCameraSource} onPhoneConnected={setIsPhoneConnected} compact enableMarkerDetection columnCount={4} onCalibrationChange={handleCalibrationChange} showRectifiedView={false} forceRawMode /> {/* Capture controls - show when camera is ready */} {canCapture && ( <div className={css({ mt: 3 })}> {/* Auto-capture toggle */} <button type="button" onClick={() => setIsAutoCapturing(!isAutoCapturing)} className={css({ width: '100%', py: 3, bg: isAutoCapturing ? 'red.600' : 'green.600', color: 'white', borderRadius: 'md', border: 'none', cursor: 'pointer', fontWeight: 'bold', fontSize: 'md', _hover: { bg: isAutoCapturing ? 'red.500' : 'green.500' }, transition: 'all 0.2s', })} > {isAutoCapturing ? '⏹ Stop Capturing' : '▶ Start Auto-Capture'} </button> {/* Status panel */} <div className={css({ mt: 2, p: 2, bg: isAutoCapturing ? markersCurrentlyVisible ? 'green.900/30' : 'yellow.900/30' : 'gray.800', border: '1px solid', borderColor: isAutoCapturing ? markersCurrentlyVisible ? 'green.700/50' : 'yellow.700/50' : 'gray.700', borderRadius: 'md', fontSize: 'sm', })} > {isAutoCapturing ? ( <div className={css({ display: 'flex', flexDirection: 'column', gap: 1, })} > {/* Live marker status */} <div className={css({ display: 'flex', alignItems: 'center', gap: 2, color: markersCurrentlyVisible ? 'green.300' : 'yellow.300', })} > {markersCurrentlyVisible ? ( <> <span className={css({ display: 'inline-block', width: '8px', height: '8px', borderRadius: 'full', bg: 'green.400', animation: 'pulse 1s infinite', })} /> <span>Markers visible — auto-capturing</span> </> ) : ( <> <span>⚠️</span> <span>Waiting for markers...</span> </> )} </div> {/* Last capture status */} {lastCaptureStatus && ( <div className={css({ fontSize: 'xs', color: lastCaptureStatus.success ? 'green.400' : 'red.400', })} > {lastCaptureStatus.success ? '✓' : '✗'} {lastCaptureStatus.message} </div> )} </div> ) : ( <div className={css({ color: 'gray.400', textAlign: 'center' })}> Click "Start Auto-Capture" then point camera at markers </div> )} </div> </div> )} {/* Instructions */} <div className={css({ fontSize: 'xs', color: 'gray.500', mt: 3 })}> <p className={css({ fontWeight: 'medium', mb: 1 })}>How it works:</p> <p>1. Click "Start Auto-Capture" to begin</p> <p>2. Point camera at abacus with all 4 ArUco markers visible</p> <p>3. Frames auto-capture rapidly (~5/sec) when markers detected</p> <p>4. Move the abacus/camera to vary angle, lighting, distance</p> <p>5. Click "Stop Capturing" when done</p> </div> </div> ) } |