All files / web/src/app/api/vision-training/samples route.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import fs from 'fs'
import path from 'path'
import { withAuth } from '@/lib/auth/withAuth'

// Force dynamic rendering - this route reads from disk which changes at runtime
export const dynamic = 'force-dynamic'

// Data directories for each model type
const COLUMN_CLASSIFIER_DIR = path.join(process.cwd(), 'data/vision-training/collected')
const BOUNDARY_DETECTOR_DIR = path.join(process.cwd(), 'data/vision-training/boundary-frames')

type DataQuality = 'none' | 'insufficient' | 'minimal' | 'good' | 'excellent'

interface DigitSample {
  count: number
  samplePath: string | null
  // For background tiling - random selection of image paths
  tilePaths: string[]
}

// Column classifier response (digit images)
interface ColumnClassifierSamplesResponse {
  type: 'column-classifier'
  digits: Record<number, DigitSample>
  totalImages: number
  hasData: boolean
  dataQuality: DataQuality
}

// Boundary detector response (full frame images)
interface BoundaryDetectorSamplesResponse {
  type: 'boundary-detector'
  totalFrames: number
  hasData: boolean
  dataQuality: DataQuality
  deviceCount: number
  samplePaths: string[]
}

type SamplesResponse = ColumnClassifierSamplesResponse | BoundaryDetectorSamplesResponse

/**
 * GET /api/vision-training/samples?type=column-classifier|boundary-detector
 *
 * Returns sample data for the specified model type.
 * - column-classifier: Returns digit images (0-9) with counts
 * - boundary-detector: Returns frame images with corner annotations
 */
export const GET = withAuth(
  async (request) => {
    const searchParams = request.nextUrl.searchParams
    const modelType = searchParams.get('type') || 'column-classifier'

    try {
      if (modelType === 'boundary-detector') {
        return getBoundaryDetectorSamples()
      }
      return getColumnClassifierSamples()
    } catch (error) {
      console.error('[vision-training/samples] Error:', error)
      return Response.json({ error: 'Failed to read training samples' }, { status: 500 })
    }
  },
  { role: 'admin' }
)

/**
 * Get column classifier samples (digit images)
 */
function getColumnClassifierSamples(): Response {
  const digits: Record<number, DigitSample> = {}
  let totalImages = 0

  // Initialize all digits
  for (let d = 0; d <= 9; d++) {
    digits[d] = { count: 0, samplePath: null, tilePaths: [] }
  }

  // Check if data directory exists
  if (!fs.existsSync(COLUMN_CLASSIFIER_DIR)) {
    return Response.json({
      type: 'column-classifier',
      digits,
      totalImages: 0,
      hasData: false,
      dataQuality: 'none',
    } satisfies ColumnClassifierSamplesResponse)
  }

  // Scan each digit directory
  for (let d = 0; d <= 9; d++) {
    const digitDir = path.join(COLUMN_CLASSIFIER_DIR, String(d))

    if (!fs.existsSync(digitDir)) {
      continue
    }

    const files = fs
      .readdirSync(digitDir)
      .filter((f) => /\.(png|jpg|jpeg|webp)$/i.test(f))
      .sort() // Consistent ordering

    const count = files.length
    totalImages += count

    if (count > 0) {
      // Pick a representative sample (middle of the list for variety)
      const sampleIndex = Math.floor(count / 2)
      const sampleFile = files[sampleIndex]

      // Pick random files for background tiling (up to 5 per digit)
      const tileCount = Math.min(5, count)
      const tileIndices = new Set<number>()
      while (tileIndices.size < tileCount) {
        tileIndices.add(Math.floor(Math.random() * count))
      }
      const tilePaths = Array.from(tileIndices).map(
        (i) => `/api/vision-training/images/${d}/${files[i]}`
      )

      digits[d] = {
        count,
        samplePath: `/api/vision-training/images/${d}/${sampleFile}`,
        tilePaths,
      }
    }
  }

  // Determine data quality based on total and distribution
  let dataQuality: DataQuality = 'none'
  const digitCounts = Object.values(digits).map((d) => d.count)
  const minCount = Math.min(...digitCounts)
  const avgCount = totalImages / 10

  if (totalImages === 0) {
    dataQuality = 'none'
  } else if (totalImages < 50 || minCount < 3) {
    dataQuality = 'insufficient'
  } else if (totalImages < 200 || minCount < 10) {
    dataQuality = 'minimal'
  } else if (totalImages < 500 || avgCount < 40) {
    dataQuality = 'good'
  } else {
    dataQuality = 'excellent'
  }

  return Response.json({
    type: 'column-classifier',
    digits,
    totalImages,
    hasData: totalImages > 0,
    dataQuality,
  } satisfies ColumnClassifierSamplesResponse)
}

/**
 * Get boundary detector samples (frame images with corners)
 */
function getBoundaryDetectorSamples(): Response {
  let totalFrames = 0
  let deviceCount = 0
  const samplePaths: string[] = []

  // Check if data directory exists
  if (!fs.existsSync(BOUNDARY_DETECTOR_DIR)) {
    return Response.json({
      type: 'boundary-detector',
      totalFrames: 0,
      hasData: false,
      dataQuality: 'none',
      deviceCount: 0,
      samplePaths: [],
    } satisfies BoundaryDetectorSamplesResponse)
  }

  // Scan the boundary frames directory
  // Expected structure: boundary-frames/{device-id}/{frame-timestamp}.png
  // Each frame should have a corresponding .json file with corner annotations
  const entries = fs.readdirSync(BOUNDARY_DETECTOR_DIR, {
    withFileTypes: true,
  })

  for (const entry of entries) {
    if (entry.isDirectory()) {
      // Device subdirectory
      deviceCount++
      const deviceDir = path.join(BOUNDARY_DETECTOR_DIR, entry.name)
      const files = fs.readdirSync(deviceDir).filter((f) => /\.(png|jpg|jpeg|webp)$/i.test(f))

      totalFrames += files.length

      // Pick a sample image from this device
      if (files.length > 0 && samplePaths.length < 5) {
        const sampleFile = files[Math.floor(files.length / 2)]
        samplePaths.push(`/api/vision-training/boundary-images/${entry.name}/${sampleFile}`)
      }
    } else if (/\.(png|jpg|jpeg|webp)$/i.test(entry.name)) {
      // Direct file in boundary-frames directory (no device subdirectory)
      totalFrames++
      if (samplePaths.length < 5) {
        samplePaths.push(`/api/vision-training/boundary-images/${entry.name}`)
      }
    }
  }

  // Determine data quality
  let dataQuality: DataQuality = 'none'
  if (totalFrames === 0) {
    dataQuality = 'none'
  } else if (totalFrames < 50) {
    dataQuality = 'insufficient'
  } else if (totalFrames < 200) {
    dataQuality = 'minimal'
  } else if (totalFrames < 500) {
    dataQuality = 'good'
  } else {
    dataQuality = 'excellent'
  }

  return Response.json({
    type: 'boundary-detector',
    totalFrames,
    hasData: totalFrames > 0,
    dataQuality,
    deviceCount,
    samplePaths,
  } satisfies BoundaryDetectorSamplesResponse)
}