All files / web/src/hooks useAbacusVision.ts

0% Statements 0/594
0% Branches 0/1
0% Functions 0/1
0% Lines 0/594

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 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 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
'use client'

import { useCallback, useEffect, useRef, useState } from 'react'
import {
  cleanupArucoDetector,
  detectMarkers,
  initArucoDetector,
  isArucoAvailable,
  loadAruco,
} from '@/lib/vision/arucoDetection'
import {
  analyzeColumns,
  analysesToDigits,
  digitsToNumber as cvDigitsToNumber,
} from '@/lib/vision/beadDetector'
import { digitsToNumber, getMinConfidence, processVideoFrame } from '@/lib/vision/frameProcessor'
import type {
  CalibrationGrid,
  CalibrationMode,
  MarkerDetectionStatus,
  UseAbacusVisionReturn,
} from '@/types/vision'
import { useBoundaryDetector } from './useBoundaryDetector'
import { useCameraCalibration } from './useCameraCalibration'
import { useColumnClassifier } from './useColumnClassifier'
import { useDeskViewCamera } from './useDeskViewCamera'
import { useFrameStability } from './useFrameStability'

export interface UseAbacusVisionOptions {
  /** Number of abacus columns to detect */
  columnCount?: number
  /** Called when a stable value is detected */
  onValueDetected?: (value: number) => void
  /** Initial calibration mode (default: 'auto') */
  initialCalibrationMode?: CalibrationMode
}

/**
 * useAbacusVision - Primary coordinator hook for abacus vision detection
 *
 * Combines camera management, calibration, and frame processing into
 * a single hook that outputs stable detected values.
 *
 * Usage:
 * ```tsx
 * const vision = useAbacusVision({
 *   columnCount: 5,
 *   onValueDetected: (value) => setDockedValue(value)
 * })
 *
 * return (
 *   <VisionCameraFeed
 *     videoStream={vision.videoStream}
 *     calibration={vision.calibrationGrid}
 *   />
 * )
 * ```
 */
export function useAbacusVision(options: UseAbacusVisionOptions = {}): UseAbacusVisionReturn {
  const { columnCount = 5, onValueDetected, initialCalibrationMode = 'auto' } = options

  // State
  const [isEnabled, setIsEnabled] = useState(false)
  const [isDetecting, setIsDetecting] = useState(false)
  const [calibrationMode, setCalibrationMode] = useState<CalibrationMode>(initialCalibrationMode)
  const [markerDetection, setMarkerDetection] = useState<MarkerDetectionStatus>({
    isAvailable: false,
    allMarkersFound: false,
    markersFound: 0,
    detectedIds: [],
  })

  // Sub-hooks
  const camera = useDeskViewCamera()
  const calibration = useCameraCalibration()
  const stability = useFrameStability()
  const classifier = useColumnClassifier()
  const boundaryDetector = useBoundaryDetector({
    enabled: isEnabled && calibrationMode === 'marker-free',
    columnCount,
  })

  // Classifier state
  const [columnConfidences, setColumnConfidences] = useState<number[]>([])
  const [isClassifierReady, setIsClassifierReady] = useState(false)

  // Video element ref for frame capture
  const videoRef = useRef<HTMLVideoElement | null>(null)
  const canvasRef = useRef<HTMLCanvasElement | null>(null)
  const animationFrameRef = useRef<number | null>(null)
  const markerDetectionFrameRef = useRef<number | null>(null)

  // Track previous stable value to avoid duplicate callbacks
  const lastStableValueRef = useRef<number | null>(null)

  // Throttle detection (CV is fast, 10fps is plenty)
  const lastInferenceTimeRef = useRef<number>(0)
  const INFERENCE_INTERVAL_MS = 100 // 10fps

  // Ref for calibration functions to avoid infinite loop in auto-calibration effect
  const calibrationRef = useRef(calibration)
  calibrationRef.current = calibration

  // Sync device ID to calibration hook when camera device changes
  useEffect(() => {
    if (camera.currentDevice?.deviceId) {
      calibration.setDeviceId(camera.currentDevice.deviceId)
    }
  }, [camera.currentDevice?.deviceId, calibration])

  // Load and initialize ArUco on mount
  useEffect(() => {
    let cancelled = false

    const initAruco = async () => {
      try {
        await loadAruco()
        if (cancelled) return

        const available = isArucoAvailable()
        setMarkerDetection((prev) => ({ ...prev, isAvailable: available }))
        if (available) {
          initArucoDetector()
        }
      } catch (err) {
        console.error('[ArUco] Failed to load:', err)
      }
    }

    initAruco()
    return () => {
      cancelled = true
    }
  }, [])

  // Cleanup ArUco detector on unmount
  useEffect(() => {
    return () => {
      cleanupArucoDetector()
    }
  }, [])

  // Auto-calibration loop using ArUco markers
  useEffect(() => {
    if (!isEnabled || !camera.videoStream || calibrationMode !== 'auto') {
      if (markerDetectionFrameRef.current) {
        cancelAnimationFrame(markerDetectionFrameRef.current)
        markerDetectionFrameRef.current = null
      }
      return
    }

    // Get video element from stream
    const videoElements = document.querySelectorAll('video')
    let video: HTMLVideoElement | null = null
    for (const el of videoElements) {
      if (el.srcObject === camera.videoStream) {
        video = el
        break
      }
    }

    if (!video) return

    let running = true

    const detectLoop = () => {
      if (!running || !video || video.readyState < 2) {
        if (running) {
          markerDetectionFrameRef.current = requestAnimationFrame(detectLoop)
        }
        return
      }

      const result = detectMarkers(video)

      setMarkerDetection({
        isAvailable: true,
        allMarkersFound: result.allMarkersFound,
        markersFound: result.markersFound,
        detectedIds: Array.from(result.markers.keys()),
      })

      // Auto-update calibration when all markers found
      if (result.allMarkersFound && result.quadCorners) {
        const grid: CalibrationGrid = {
          roi: {
            x: Math.min(result.quadCorners.topLeft.x, result.quadCorners.bottomLeft.x),
            y: Math.min(result.quadCorners.topLeft.y, result.quadCorners.topRight.y),
            width:
              Math.max(result.quadCorners.topRight.x, result.quadCorners.bottomRight.x) -
              Math.min(result.quadCorners.topLeft.x, result.quadCorners.bottomLeft.x),
            height:
              Math.max(result.quadCorners.bottomLeft.y, result.quadCorners.bottomRight.y) -
              Math.min(result.quadCorners.topLeft.y, result.quadCorners.topRight.y),
          },
          corners: result.quadCorners,
          columnCount,
          columnDividers: Array.from({ length: columnCount - 1 }, (_, i) => (i + 1) / columnCount),
          rotation: 0,
        }
        calibrationRef.current.updateCalibration(grid)
        if (!calibrationRef.current.isCalibrated) {
          calibrationRef.current.finishCalibration()
        }
      }

      markerDetectionFrameRef.current = requestAnimationFrame(detectLoop)
    }

    detectLoop()

    return () => {
      running = false
      if (markerDetectionFrameRef.current) {
        cancelAnimationFrame(markerDetectionFrameRef.current)
        markerDetectionFrameRef.current = null
      }
    }
  }, [isEnabled, camera.videoStream, calibrationMode, columnCount])

  // Marker-free calibration loop using boundary detector ML model
  const markerFreeFrameRef = useRef<number | null>(null)
  const markerFreeLastTimeRef = useRef<number>(0)
  const MARKER_FREE_INTERVAL_MS = 200 // 5fps for inference

  useEffect(() => {
    if (!isEnabled || !camera.videoStream || calibrationMode !== 'marker-free') {
      if (markerFreeFrameRef.current) {
        cancelAnimationFrame(markerFreeFrameRef.current)
        markerFreeFrameRef.current = null
      }
      return
    }

    // Check if boundary detector is ready
    if (!boundaryDetector.isReady && !boundaryDetector.isLoading) {
      boundaryDetector.preload()
      return
    }

    if (!boundaryDetector.isReady) {
      return // Still loading
    }

    // Get video element from stream
    const videoElements = document.querySelectorAll('video')
    let video: HTMLVideoElement | null = null
    for (const el of videoElements) {
      if (el.srcObject === camera.videoStream) {
        video = el
        break
      }
    }

    if (!video) return

    let running = true

    const detectLoop = async () => {
      if (!running || !video || video.readyState < 2) {
        if (running) {
          markerFreeFrameRef.current = requestAnimationFrame(detectLoop)
        }
        return
      }

      // Throttle inference
      const now = performance.now()
      if (now - markerFreeLastTimeRef.current < MARKER_FREE_INTERVAL_MS) {
        markerFreeFrameRef.current = requestAnimationFrame(detectLoop)
        return
      }
      markerFreeLastTimeRef.current = now

      // Run boundary detection (updates internal state in hook)
      await boundaryDetector.detectFromVideo(video)

      // If we have stable corners, update calibration
      if (boundaryDetector.detectedCorners && boundaryDetector.confidence > 0.7) {
        const grid = boundaryDetector.createCalibrationGrid()
        if (grid) {
          calibrationRef.current.updateCalibration(grid)
          if (!calibrationRef.current.isCalibrated) {
            calibrationRef.current.finishCalibration()
          }
        }
      }

      if (running) {
        markerFreeFrameRef.current = requestAnimationFrame(detectLoop)
      }
    }

    detectLoop()

    return () => {
      running = false
      if (markerFreeFrameRef.current) {
        cancelAnimationFrame(markerFreeFrameRef.current)
        markerFreeFrameRef.current = null
      }
    }
  }, [
    isEnabled,
    camera.videoStream,
    calibrationMode,
    boundaryDetector.isReady,
    boundaryDetector.isLoading,
    boundaryDetector.detectFromVideo,
    boundaryDetector.detectedCorners,
    boundaryDetector.confidence,
    boundaryDetector.createCalibrationGrid,
    boundaryDetector.preload,
  ])

  /**
   * Enable vision mode - start camera and detection
   */
  const enable = useCallback(async () => {
    setIsEnabled(true)
    await camera.requestCamera()
  }, [camera])

  /**
   * Disable vision mode - stop camera and detection
   */
  const disable = useCallback(() => {
    setIsEnabled(false)
    setIsDetecting(false)
    camera.stopCamera()
    stability.reset()

    if (animationFrameRef.current) {
      cancelAnimationFrame(animationFrameRef.current)
      animationFrameRef.current = null
    }
  }, [camera, stability])

  /**
   * Start calibration mode
   */
  const startCalibration = useCallback(() => {
    calibration.startCalibration()
  }, [calibration])

  /**
   * Finish calibration
   */
  const finishCalibration = useCallback(
    (grid: CalibrationGrid) => {
      calibration.updateCalibration(grid)
      calibration.finishCalibration()
    },
    [calibration]
  )

  /**
   * Cancel calibration
   */
  const cancelCalibration = useCallback(() => {
    calibration.cancelCalibration()
  }, [calibration])

  /**
   * Select specific camera
   */
  const selectCamera = useCallback(
    (deviceId: string) => {
      camera.requestCamera(deviceId)
    },
    [camera]
  )

  /**
   * Reset calibration
   */
  const resetCalibration = useCallback(() => {
    calibration.resetCalibration()
  }, [calibration])

  /**
   * Process a video frame for detection using CV-based bead detection
   */
  const processFrame = useCallback(async () => {
    // Throttle inference for performance (10fps)
    const now = performance.now()
    if (now - lastInferenceTimeRef.current < INFERENCE_INTERVAL_MS) {
      return
    }
    lastInferenceTimeRef.current = now

    // Get video element from camera stream
    const videoElements = document.querySelectorAll('video')
    let video: HTMLVideoElement | null = null
    for (const el of videoElements) {
      if (el.srcObject === camera.videoStream) {
        video = el
        break
      }
    }

    if (!video || video.readyState < 2) return
    if (!calibration.isCalibrated || !calibration.calibration) return

    // Check if hand is detected (motion) - pause classification during motion
    if (stability.isHandDetected) return

    // Process video frame into column strips
    const columnImages = processVideoFrame(video, calibration.calibration)
    if (columnImages.length === 0) return

    // Use CV-based bead detection instead of ML
    const analyses = analyzeColumns(columnImages)
    const { digits, confidences, minConfidence } = analysesToDigits(analyses)

    // Log analysis for debugging
    console.log(
      '[CV] Bead analysis:',
      analyses.map((a) => ({
        digit: a.digit,
        conf: a.confidence.toFixed(2),
        heaven: a.heavenActive ? '5' : '0',
        earth: a.earthActiveCount,
        bar: a.reckoningBarPosition.toFixed(2),
      }))
    )

    // Update column confidences
    setColumnConfidences(confidences)

    // Convert digits to number
    const detectedValue = cvDigitsToNumber(digits)

    // Push to stability buffer
    stability.pushFrame(detectedValue, minConfidence)
  }, [camera.videoStream, calibration.isCalibrated, calibration.calibration, stability])

  /**
   * Detection loop
   */
  const runDetectionLoop = useCallback(() => {
    if (!isEnabled || !calibration.isCalibrated || calibration.isCalibrating) {
      return
    }

    setIsDetecting(true)

    // Process frame asynchronously, then continue loop
    processFrame().finally(() => {
      if (isEnabled && calibration.isCalibrated && !calibration.isCalibrating) {
        animationFrameRef.current = requestAnimationFrame(runDetectionLoop)
      }
    })
  }, [isEnabled, calibration.isCalibrated, calibration.isCalibrating, processFrame])

  // Preload classifier when vision is enabled
  // Model may not exist yet (not trained) - that's ok, vision still works in manual mode
  useEffect(() => {
    if (
      isEnabled &&
      !classifier.isModelLoaded &&
      !classifier.isLoading &&
      !classifier.isModelUnavailable
    ) {
      classifier.preload().then((success) => {
        // Set ready regardless - vision can work without ML classifier
        // (manual calibration + frame capture still works)
        setIsClassifierReady(true)
        if (!success) {
          console.log('[useAbacusVision] ML classifier not available - using manual mode only')
        }
      })
    } else if (classifier.isModelUnavailable) {
      // Model doesn't exist - still allow vision in manual mode
      setIsClassifierReady(true)
    }
  }, [isEnabled, classifier])

  // Start/stop detection loop based on state
  useEffect(() => {
    if (
      isEnabled &&
      calibration.isCalibrated &&
      !calibration.isCalibrating &&
      camera.videoStream &&
      isClassifierReady
    ) {
      runDetectionLoop()
    } else {
      setIsDetecting(false)
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current)
        animationFrameRef.current = null
      }
    }

    return () => {
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current)
        animationFrameRef.current = null
      }
    }
  }, [
    isEnabled,
    calibration.isCalibrated,
    calibration.isCalibrating,
    camera.videoStream,
    isClassifierReady,
    runDetectionLoop,
  ])

  // Notify when stable value changes
  useEffect(() => {
    if (stability.stableValue !== null && stability.stableValue !== lastStableValueRef.current) {
      lastStableValueRef.current = stability.stableValue
      onValueDetected?.(stability.stableValue)
    }
  }, [stability.stableValue, onValueDetected])

  // Create hidden canvas for frame processing
  useEffect(() => {
    if (!canvasRef.current) {
      canvasRef.current = document.createElement('canvas')
    }
  }, [])

  // Cleanup animation frame on unmount (camera cleanup handled by disable())
  useEffect(() => {
    return () => {
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current)
      }
      // Note: camera.stopCamera() is called by disable() - don't duplicate
    }
  }, [])

  return {
    // Vision state
    isEnabled,
    isCalibrated: calibration.isCalibrated,
    isDetecting,
    currentDetectedValue: stability.stableValue,
    confidence: stability.currentConfidence,
    columnConfidences,

    // Classifier state
    isClassifierLoading: classifier.isLoading,
    isClassifierReady,
    classifierError: classifier.error,

    // Camera state
    isCameraLoading: camera.isLoading,
    videoStream: camera.videoStream,
    cameraError: camera.error,
    selectedDeviceId: camera.currentDevice?.deviceId ?? null,
    availableDevices: camera.availableDevices,
    isDeskViewDetected: camera.isDeskViewDetected,
    facingMode: camera.facingMode,
    isTorchOn: camera.isTorchOn,
    isTorchAvailable: camera.isTorchAvailable,

    // Calibration state
    calibrationGrid: calibration.calibration,
    isCalibrating: calibration.isCalibrating,
    calibrationMode,
    markerDetection,

    // Boundary detector state (marker-free mode)
    boundaryDetector: {
      isReady: boundaryDetector.isReady,
      isLoading: boundaryDetector.isLoading,
      isUnavailable: boundaryDetector.isUnavailable,
      confidence: boundaryDetector.confidence,
      consecutiveFrames: boundaryDetector.consecutiveFrames,
    },

    // Stability state
    isHandDetected: stability.isHandDetected,
    consecutiveFrames: stability.consecutiveFrames,

    // Actions
    enable,
    disable,
    startCalibration,
    finishCalibration,
    cancelCalibration,
    selectCamera,
    resetCalibration,
    setCalibrationMode,
    flipCamera: camera.flipCamera,
    toggleTorch: camera.toggleTorch,
  }
}