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

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

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

// Force dynamic rendering
export const dynamic = 'force-dynamic'

/**
 * Manifest item for column classifier
 */
interface ColumnManifestItem {
  type: 'column'
  digit: number
  filename: string
}

/**
 * Manifest item for boundary detector
 */
interface BoundaryManifestItem {
  type: 'boundary'
  deviceId: string
  baseName: string
}

type ManifestItem = ColumnManifestItem | BoundaryManifestItem

/**
 * Training manifest schema
 */
interface TrainingManifest {
  id: string
  modelType: 'column-classifier' | 'boundary-detector'
  createdAt: string
  filters: {
    captureType?: 'passive' | 'explicit' | 'all'
    deviceId?: string
    digit?: number // column-classifier only
  }
  items: ManifestItem[]
}

// Manifest storage directory
const MANIFESTS_DIR = path.join(process.cwd(), 'data/vision-training/manifests')

/**
 * Ensure the manifests directory exists
 */
async function ensureManifestsDir(): Promise<void> {
  try {
    await fs.mkdir(MANIFESTS_DIR, { recursive: true })
  } catch {
    // Directory may already exist
  }
}

/**
 * POST /api/vision-training/manifests
 *
 * Create a new training manifest from filtered items.
 *
 * Request body:
 * {
 *   modelType: 'column-classifier' | 'boundary-detector',
 *   filters: { captureType?, deviceId?, digit? },
 *   items: ManifestItem[]
 * }
 *
 * Response:
 * {
 *   manifestId: string,
 *   itemCount: number
 * }
 */
export const POST = withAuth(
  async (request) => {
    try {
      const body = await request.json()
      const { modelType, filters, items } = body

      // Validate required fields
      if (!modelType || !['column-classifier', 'boundary-detector'].includes(modelType)) {
        return new Response(
          JSON.stringify({
            error: 'Invalid modelType. Must be "column-classifier" or "boundary-detector".',
          }),
          { status: 400, headers: { 'Content-Type': 'application/json' } }
        )
      }

      if (!Array.isArray(items) || items.length === 0) {
        return new Response(
          JSON.stringify({ error: 'Items array is required and must not be empty.' }),
          { status: 400, headers: { 'Content-Type': 'application/json' } }
        )
      }

      // Validate items based on model type
      for (const item of items) {
        if (modelType === 'column-classifier') {
          if (
            item.type !== 'column' ||
            typeof item.digit !== 'number' ||
            typeof item.filename !== 'string'
          ) {
            return new Response(
              JSON.stringify({
                error: 'Invalid column manifest item. Required: type="column", digit, filename.',
              }),
              { status: 400, headers: { 'Content-Type': 'application/json' } }
            )
          }
        } else if (modelType === 'boundary-detector') {
          if (
            item.type !== 'boundary' ||
            typeof item.deviceId !== 'string' ||
            typeof item.baseName !== 'string'
          ) {
            return new Response(
              JSON.stringify({
                error:
                  'Invalid boundary manifest item. Required: type="boundary", deviceId, baseName.',
              }),
              { status: 400, headers: { 'Content-Type': 'application/json' } }
            )
          }
        }
      }

      // Create manifest
      const manifestId = createId()
      const manifest: TrainingManifest = {
        id: manifestId,
        modelType,
        createdAt: new Date().toISOString(),
        filters: filters || {},
        items,
      }

      // Ensure directory exists and write manifest
      await ensureManifestsDir()
      const manifestPath = path.join(MANIFESTS_DIR, `${manifestId}.json`)
      await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2), 'utf-8')

      return new Response(
        JSON.stringify({
          manifestId,
          itemCount: items.length,
        }),
        { status: 201, headers: { 'Content-Type': 'application/json' } }
      )
    } catch (error) {
      console.error('[Manifests API] Error creating manifest:', error)
      return new Response(
        JSON.stringify({ error: 'Failed to create manifest', details: String(error) }),
        { status: 500, headers: { 'Content-Type': 'application/json' } }
      )
    }
  },
  { role: 'admin' }
)

/**
 * GET /api/vision-training/manifests
 *
 * List all manifests, optionally filtered by modelType.
 *
 * Query params:
 * - modelType (optional): Filter by model type
 */
export const GET = withAuth(
  async (request) => {
    try {
      const { searchParams } = new URL(request.url)
      const modelTypeFilter = searchParams.get('modelType')

      await ensureManifestsDir()

      // Read all manifest files
      const files = await fs.readdir(MANIFESTS_DIR)
      const manifests: TrainingManifest[] = []

      for (const file of files) {
        if (!file.endsWith('.json')) continue

        try {
          const content = await fs.readFile(path.join(MANIFESTS_DIR, file), 'utf-8')
          const manifest = JSON.parse(content) as TrainingManifest

          // Apply model type filter if specified
          if (modelTypeFilter && manifest.modelType !== modelTypeFilter) {
            continue
          }

          manifests.push(manifest)
        } catch {
          // Skip invalid files
          console.warn(`[Manifests API] Skipping invalid manifest file: ${file}`)
        }
      }

      // Sort by creation date (newest first)
      manifests.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())

      return new Response(
        JSON.stringify({
          manifests: manifests.map((m) => ({
            id: m.id,
            modelType: m.modelType,
            createdAt: m.createdAt,
            itemCount: m.items.length,
            filters: m.filters,
          })),
        }),
        { headers: { 'Content-Type': 'application/json' } }
      )
    } catch (error) {
      console.error('[Manifests API] Error listing manifests:', error)
      return new Response(
        JSON.stringify({ error: 'Failed to list manifests', details: String(error) }),
        { status: 500, headers: { 'Content-Type': 'application/json' } }
      )
    }
  },
  { role: 'admin' }
)