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

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

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                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * Background Task API for Vision Training
 *
 * POST /api/vision-training/train/task
 *   - Start training as a background task
 *   - Returns a taskId for Socket.IO subscription
 *
 * GET /api/vision-training/train/task
 *   - Get active training task (if any)
 *
 * DELETE /api/vision-training/train/task
 *   - Cancel the active training task
 *
 * PUT /api/vision-training/train/task
 *   - Request early stop (save model at end of current epoch)
 */

import { NextResponse } from 'next/server'
import { eq } from 'drizzle-orm'
import { db } from '@/db'
import { backgroundTasks } from '@/db/schema/background-tasks'
import { startVisionTraining, requestEarlyStop } from '@/lib/tasks/vision-training'
import { cancelTask } from '@/lib/task-manager'
import { withAuth } from '@/lib/auth/withAuth'

export const dynamic = 'force-dynamic'

/**
 * POST - Start vision training as a background task
 */
export const POST = withAuth(
  async (request: Request) => {
    try {
      // Check for already-running training task
      const existingTask = await db
        .select()
        .from(backgroundTasks)
        .where(eq(backgroundTasks.type, 'vision-training'))
        .all()
        .then((tasks) => tasks.find((t) => t.status === 'running' || t.status === 'pending'))

      if (existingTask) {
        return NextResponse.json({
          taskId: existingTask.id,
          status: 'already_running',
          message: 'Training already in progress',
        })
      }

      // Parse request body
      let config: {
        modelType?: 'column-classifier' | 'boundary-detector'
        epochs?: number
        batchSize?: number
        validationSplit?: number
        noAugmentation?: boolean
        colorAugmentation?: boolean
        manifestId?: string
      } = {}
      try {
        const body = await request.text()
        if (body) {
          config = JSON.parse(body)
        }
      } catch {
        // Use defaults if body parsing fails
      }

      // Start the background task
      const taskId = await startVisionTraining({
        modelType: config.modelType ?? 'column-classifier',
        epochs: config.epochs,
        batchSize: config.batchSize,
        validationSplit: config.validationSplit,
        noAugmentation: config.noAugmentation,
        colorAugmentation: config.colorAugmentation,
        manifestId: config.manifestId,
      })

      return NextResponse.json({
        taskId,
        status: 'started',
        message: 'Training task started',
      })
    } catch (error) {
      console.error('[VisionTrainingTaskAPI] Error starting training task:', error)
      return NextResponse.json(
        { error: error instanceof Error ? error.message : 'Failed to start training' },
        { status: 500 }
      )
    }
  },
  { role: 'admin' }
)

/**
 * GET - Check for active training task
 */
export const GET = withAuth(
  async () => {
    try {
      const tasks = await db
        .select({
          id: backgroundTasks.id,
          status: backgroundTasks.status,
          progress: backgroundTasks.progress,
          progressMessage: backgroundTasks.progressMessage,
        })
        .from(backgroundTasks)
        .where(eq(backgroundTasks.type, 'vision-training'))
        .all()

      const activeTask = tasks.find((t) => t.status === 'running' || t.status === 'pending')

      if (activeTask) {
        return NextResponse.json({
          taskId: activeTask.id,
          status: activeTask.status,
          progress: activeTask.progress,
          progressMessage: activeTask.progressMessage,
        })
      }

      return NextResponse.json({
        taskId: null,
        status: 'none',
        message: 'No active training task',
      })
    } catch (error) {
      console.error('[VisionTrainingTaskAPI] Error checking task:', error)
      return NextResponse.json({ error: 'Failed to check task status' }, { status: 500 })
    }
  },
  { role: 'admin' }
)

/**
 * DELETE - Cancel the active training task
 */
export const DELETE = withAuth(
  async () => {
    try {
      const tasks = await db
        .select()
        .from(backgroundTasks)
        .where(eq(backgroundTasks.type, 'vision-training'))
        .all()

      const activeTask = tasks.find((t) => t.status === 'running' || t.status === 'pending')

      if (!activeTask) {
        return NextResponse.json({ message: 'No training in progress' })
      }

      const cancelled = await cancelTask(activeTask.id)
      return NextResponse.json({
        cancelled,
        message: cancelled ? 'Training cancellation requested' : 'Could not cancel training',
      })
    } catch (error) {
      console.error('[VisionTrainingTaskAPI] Error cancelling:', error)
      return NextResponse.json({ error: 'Failed to cancel training' }, { status: 500 })
    }
  },
  { role: 'admin' }
)

/**
 * PUT - Request early stop (save model at end of current epoch)
 */
export const PUT = withAuth(
  async () => {
    try {
      const tasks = await db
        .select()
        .from(backgroundTasks)
        .where(eq(backgroundTasks.type, 'vision-training'))
        .all()

      const activeTask = tasks.find((t) => t.status === 'running' || t.status === 'pending')

      if (!activeTask) {
        return NextResponse.json({ message: 'No training in progress' })
      }

      const stopped = requestEarlyStop(activeTask.id)
      return NextResponse.json({
        stopped,
        message: stopped
          ? 'Early stop requested - model will be saved at end of current epoch'
          : 'Could not request early stop (training may not be running on this pod)',
      })
    } catch (error) {
      console.error('[VisionTrainingTaskAPI] Error requesting early stop:', error)
      return NextResponse.json({ error: 'Failed to request early stop' }, { status: 500 })
    }
  },
  { role: 'admin' }
)