All files / web/src/hooks useColumnClassifier.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                         
'use client'

import { useCallback, useEffect, useRef, useState } from 'react'
import type { ClassificationResult, BeadPositionResult } from '@/lib/vision/columnClassifier'

export interface UseColumnClassifierReturn {
  /** Whether the model is loaded and ready */
  isModelLoaded: boolean
  /** Whether the model is currently loading */
  isLoading: boolean
  /** Whether the model is unavailable (doesn't exist / failed to load) */
  isModelUnavailable: boolean
  /** Error message if model failed to load */
  error: string | null

  /** Classify a single column image */
  classifyColumn: (imageData: ImageData) => Promise<ClassificationResult | null>

  /** Classify multiple column images */
  classifyColumns: (columnImages: ImageData[]) => Promise<{
    digits: number[]
    confidences: number[]
    beadPositions: BeadPositionResult[]
  } | null>

  /** Preload the model. Returns true if successful, false if unavailable */
  preload: () => Promise<boolean>

  /** Dispose of the model */
  dispose: () => void

  /** Reset model state to allow retrying after a failure */
  reset: () => Promise<void>
}

/**
 * Hook for using the TensorFlow.js column classifier
 *
 * Handles lazy loading of the model and provides classification methods.
 *
 * Usage:
 * ```tsx
 * const classifier = useColumnClassifier()
 *
 * // Preload model when component mounts
 * useEffect(() => {
 *   classifier.preload()
 * }, [])
 *
 * // Classify columns
 * const results = await classifier.classifyColumns(columnImages)
 * ```
 */
export function useColumnClassifier(): UseColumnClassifierReturn {
  const [isModelLoaded, setIsModelLoaded] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [isModelUnavailable, setIsModelUnavailable] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Lazy-loaded classifier module
  const classifierRef = useRef<typeof import('@/lib/vision/columnClassifier') | null>(null)

  /**
   * Lazy load the classifier module
   */
  const loadClassifier = useCallback(async () => {
    if (classifierRef.current) return classifierRef.current

    const classifier = await import('@/lib/vision/columnClassifier')
    classifierRef.current = classifier
    return classifier
  }, [])

  /**
   * Preload the model
   * Returns true if model loaded successfully, false if unavailable
   */
  const preload = useCallback(async (): Promise<boolean> => {
    if (isModelLoaded) return true
    if (isModelUnavailable) return false
    if (isLoading) return false

    setIsLoading(true)
    setError(null)

    try {
      const classifier = await loadClassifier()
      const success = await classifier.preloadModel()

      if (success) {
        setIsModelLoaded(true)
        return true
      } else {
        setIsModelUnavailable(true)
        return false
      }
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Failed to load model'
      setError(message)
      setIsModelUnavailable(true)
      console.error('[useColumnClassifier] Model loading failed:', err)
      return false
    } finally {
      setIsLoading(false)
    }
  }, [isModelLoaded, isModelUnavailable, isLoading, loadClassifier])

  /**
   * Classify a single column
   */
  const classifyColumn = useCallback(
    async (imageData: ImageData): Promise<ClassificationResult | null> => {
      try {
        const classifier = await loadClassifier()

        // Auto-load model if not loaded
        if (!classifier.isModelLoaded()) {
          await classifier.preloadModel()
          setIsModelLoaded(true)
        }

        return await classifier.classifyColumn(imageData)
      } catch (err) {
        console.error('[useColumnClassifier] Classification failed:', err)
        return null
      }
    },
    [loadClassifier]
  )

  /**
   * Classify multiple columns
   */
  const classifyColumns = useCallback(
    async (
      columnImages: ImageData[]
    ): Promise<{
      digits: number[]
      confidences: number[]
      beadPositions: BeadPositionResult[]
    } | null> => {
      if (columnImages.length === 0) return { digits: [], confidences: [], beadPositions: [] }

      try {
        const classifier = await loadClassifier()

        // Auto-load model if not loaded
        if (!classifier.isModelLoaded()) {
          await classifier.preloadModel()
          setIsModelLoaded(true)
        }

        const results = await classifier.classifyColumns(columnImages)

        // Model unavailable
        if (!results) return null

        return {
          digits: results.map((r) => r.digit),
          confidences: results.map((r) => r.confidence),
          beadPositions: results.map((r) => r.beadPosition),
        }
      } catch (err) {
        console.error('[useColumnClassifier] Batch classification failed:', err)
        return null
      }
    },
    [loadClassifier]
  )

  /**
   * Dispose of the model
   */
  const dispose = useCallback(() => {
    if (classifierRef.current) {
      classifierRef.current.disposeModel()
      setIsModelLoaded(false)
    }
  }, [])

  /**
   * Reset model state to allow retrying after a failure
   */
  const reset = useCallback(async (): Promise<void> => {
    const classifier = await loadClassifier()
    classifier.resetModelState()
    setIsModelLoaded(false)
    setIsModelUnavailable(false)
    setError(null)
    setIsLoading(false)
  }, [loadClassifier])

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      // Don't dispose on unmount - model can be reused
      // Only dispose explicitly when needed
    }
  }, [])

  return {
    isModelLoaded,
    isLoading,
    isModelUnavailable,
    error,
    classifyColumn,
    classifyColumns,
    preload,
    dispose,
    reset,
  }
}