All files / web/src/lib/tasks worksheet-reparse.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
/**
 * Worksheet Re-Parsing Background Task
 *
 * Wraps the LLM-based selective problem re-parsing in a background task for:
 * - Real-time progress streaming via Socket.IO
 * - Survival across page reloads
 * - Event replay for late-joining clients
 * - Database persistence of results
 */

import { eq } from 'drizzle-orm'
import { readFile } from 'fs/promises'
import { join } from 'path'
import sharp from 'sharp'
import { z } from 'zod'
import { db } from '@/db'
import { type ParsingStatus, practiceAttachments } from '@/db/schema/practice-attachments'
import { createPersistenceMiddleware, LLM_SNAPSHOT_INTERVAL_MS, llm } from '@/lib/llm'
import { createTask, type TaskHandle } from '../task-manager'
import {
  type BoundingBox,
  CROP_PADDING,
  calculateCropRegion,
  type ParsedProblem,
  type WorksheetParsingResult,
} from '../worksheet-parsing'
import type { WorksheetReparseEvent } from './events'

/**
 * Input for worksheet re-parsing task
 */
export interface WorksheetReparseInput {
  /** Attachment ID for database association */
  attachmentId: string
  /** Player ID for database association */
  playerId: string
  /** Problem indices to re-parse (0-based) */
  problemIndices: number[]
  /** Bounding boxes for each problem (must match problemIndices length) */
  boundingBoxes: BoundingBox[]
  /** Additional context for the LLM */
  additionalContext?: string
}

/**
 * Output from worksheet re-parsing task
 */
export interface WorksheetReparseOutput {
  /** Number of problems successfully re-parsed */
  reparsedCount: number
  /** Indices of problems that were re-parsed */
  reparsedIndices: number[]
  /** Updated parsing result with merged data */
  updatedResult: WorksheetParsingResult
  /** Final status */
  status: ParsingStatus
}

// Schema for single problem re-parse response
const SingleProblemSchema = z.object({
  terms: z
    .array(z.number().int())
    .min(2)
    .max(7)
    .describe(
      'The terms (numbers) in this problem. First term is always positive. ' +
        'Negative numbers indicate subtraction. Example: "45 - 17 + 8" -> [45, -17, 8]'
    ),
  studentAnswer: z
    .number()
    .int()
    .nullable()
    .describe("The student's written answer. null if no answer is visible or answer box is empty."),
  format: z
    .enum(['vertical', 'linear'])
    .describe('Format: "vertical" for stacked column, "linear" for horizontal'),
  termsConfidence: z.number().min(0).max(1).describe('Confidence in terms reading (0-1)'),
  studentAnswerConfidence: z
    .number()
    .min(0)
    .max(1)
    .describe('Confidence in student answer reading (0-1)'),
})

/**
 * Build prompt for single problem parsing
 */
function buildSingleProblemPrompt(additionalContext?: string): string {
  let prompt = `You are analyzing a cropped image showing a SINGLE arithmetic problem from an abacus workbook.

Extract the following from this cropped problem image:
1. The problem terms (numbers being added/subtracted)
2. The student's written answer (if any)
3. The format (vertical or linear)
4. Your confidence in each reading

CRITICAL: MINUS SIGN DETECTION

Minus signs are SMALL but EXTREMELY IMPORTANT. Missing a minus sign completely changes the answer!

**How minus signs appear in VERTICAL problems:**
- A small horizontal dash/line to the LEFT of a number
- May appear as: − (minus), - (hyphen), or a short horizontal stroke
- Often smaller than you expect - LOOK CAREFULLY!
- Sometimes positioned slightly above or below the number's vertical center

**Example - the ONLY difference is that tiny minus sign:**
- NO minus: 45 + 17 + 8 = 70 → terms = [45, 17, 8]
- WITH minus: 45 - 17 + 8 = 36 → terms = [45, -17, 8]

**You MUST examine the LEFT side of each number for minus signs!**

IMPORTANT:
- The first term is always positive
- Negative numbers indicate subtraction (e.g., "45 - 17" has terms [45, -17])
- If no student answer is visible, set studentAnswer to null
- Be precise about handwritten digits - common confusions: 1/7, 4/9, 6/0, 5/8

CONFIDENCE GUIDELINES:
- 0.9-1.0: Clear, unambiguous reading
- 0.7-0.89: Slightly unclear but confident
- 0.5-0.69: Uncertain, could be misread
- Below 0.5: Very uncertain`

  if (additionalContext) {
    prompt += `\n\nADDITIONAL CONTEXT FROM USER:\n${additionalContext}`
  }

  return prompt
}

/**
 * Crop image to bounding box with padding using sharp (server-side).
 */
async function cropToBoundingBox(
  imageBuffer: Buffer,
  box: BoundingBox,
  padding: number = CROP_PADDING
): Promise<Buffer> {
  const metadata = await sharp(imageBuffer).metadata()
  const imageWidth = metadata.width ?? 1
  const imageHeight = metadata.height ?? 1

  const region = calculateCropRegion(box, imageWidth, imageHeight, padding)

  return sharp(imageBuffer)
    .extract({
      left: region.left,
      top: region.top,
      width: region.width,
      height: region.height,
    })
    .toBuffer()
}

/**
 * Start a worksheet re-parsing background task
 */
export async function startWorksheetReparse(input: WorksheetReparseInput): Promise<string> {
  // Validate required fields
  if (!input.attachmentId) {
    throw new Error('Attachment ID is required')
  }
  if (!input.playerId) {
    throw new Error('Player ID is required')
  }
  if (!input.problemIndices || input.problemIndices.length === 0) {
    throw new Error('At least one problem index is required')
  }
  if (input.problemIndices.length !== input.boundingBoxes.length) {
    throw new Error('problemIndices and boundingBoxes must have the same length')
  }

  // Clear any previous error (status will be set on completion)
  await db
    .update(practiceAttachments)
    .set({
      parsingError: null,
    })
    .where(eq(practiceAttachments.id, input.attachmentId))

  return createTask<WorksheetReparseInput, WorksheetReparseOutput, WorksheetReparseEvent>(
    'worksheet-reparse',
    input,
    async (handle, config) => {
      console.log('[WorksheetReparseTask] Handler started for attachment:', config.attachmentId)
      const { attachmentId, playerId, problemIndices, boundingBoxes, additionalContext } = config

      handle.setProgress(5, 'Initializing re-parser...')
      handle.emit({
        type: 'reparse_started',
        attachmentId,
        problemCount: problemIndices.length,
        problemIndices,
      })

      try {
        await runReparse(handle, {
          attachmentId,
          playerId,
          problemIndices,
          boundingBoxes,
          additionalContext,
        })
      } catch (error) {
        // Update DB with error
        const errorMessage = error instanceof Error ? error.message : String(error)
        await db
          .update(practiceAttachments)
          .set({
            parsingStatus: 'failed',
            parsingError: errorMessage,
          })
          .where(eq(practiceAttachments.id, attachmentId))
        throw error
      }
    }
  )
}

/**
 * Run the re-parsing process
 */
async function runReparse(
  handle: TaskHandle<WorksheetReparseOutput, WorksheetReparseEvent>,
  config: WorksheetReparseInput
): Promise<void> {
  const { attachmentId, playerId, problemIndices, boundingBoxes, additionalContext } = config

  // Get attachment record
  const attachment = await db
    .select()
    .from(practiceAttachments)
    .where(eq(practiceAttachments.id, attachmentId))
    .get()

  if (!attachment) {
    throw new Error('Attachment not found')
  }

  if (!attachment.rawParsingResult) {
    throw new Error('Attachment has not been parsed yet')
  }

  const existingResult = attachment.rawParsingResult as WorksheetParsingResult

  // Read the image file
  const uploadDir = join(process.cwd(), 'data', 'uploads', 'players', playerId)
  const filepath = join(uploadDir, attachment.filename)
  const imageBuffer = await readFile(filepath)
  const mimeType = attachment.mimeType || 'image/jpeg'

  // Build the prompt
  const prompt = buildSingleProblemPrompt(additionalContext)

  // Process each selected problem
  const reparsedProblems: Array<{
    index: number
    originalProblem: ParsedProblem
    newData: z.infer<typeof SingleProblemSchema>
  }> = []

  for (let i = 0; i < problemIndices.length; i++) {
    // Check for cancellation
    if (handle.isCancelled()) {
      handle.emit({ type: 'cancelled', reason: 'User cancelled' })
      await db
        .update(practiceAttachments)
        .set({ parsingStatus: null, parsingError: null })
        .where(eq(practiceAttachments.id, attachmentId))
      return
    }

    const problemIndex = problemIndices[i]
    const box = boundingBoxes[i]
    const originalProblem = existingResult.problems[problemIndex]

    if (!originalProblem) {
      console.warn(`[WorksheetReparseTask] Problem index ${problemIndex} not found`)
      continue
    }

    // Notify starting this problem
    const progressPercent = 10 + Math.floor((i / problemIndices.length) * 70)
    handle.setProgress(progressPercent, `Analyzing problem ${i + 1} of ${problemIndices.length}...`)
    handle.emit({
      type: 'problem_start',
      problemIndex,
      problemNumber: originalProblem.problemNumber,
      currentIndex: i,
      totalProblems: problemIndices.length,
    })

    try {
      // Crop image to bounding box
      const croppedBuffer = await cropToBoundingBox(imageBuffer, box)
      const base64Cropped = croppedBuffer.toString('base64')
      const croppedDataUrl = `data:${mimeType};base64,${base64Cropped}`

      // Create per-problem middleware-enhanced client (captures problemIndex in closure)
      const problemLLM = llm.with(
        createPersistenceMiddleware({
          snapshotIntervalMs: LLM_SNAPSHOT_INTERVAL_MS,
          onReasoning: (text, isDelta) => {
            handle.emitTransient({
              type: 'reasoning',
              problemIndex,
              text,
              isDelta,
            } as WorksheetReparseEvent)
          },
          onOutputDelta: (text) => {
            handle.emitTransient({
              type: 'output_delta',
              problemIndex,
              text,
            } as WorksheetReparseEvent)
          },
          onReasoningSnapshot: (text) => {
            handle.emit({
              type: 'reasoning_snapshot',
              problemIndex,
              text,
            } as WorksheetReparseEvent)
          },
          onOutputSnapshot: (text) => {
            handle.emit({
              type: 'output_snapshot',
              problemIndex,
              text,
            } as WorksheetReparseEvent)
          },
        })
      )

      // Stream the LLM call for this problem
      const llmStream = problemLLM.stream({
        prompt,
        images: [croppedDataUrl],
        schema: SingleProblemSchema,
        provider: 'openai',
        model: 'gpt-5.2',
        reasoning: {
          effort: 'medium',
          summary: 'auto',
        },
      })

      let problemResult: z.infer<typeof SingleProblemSchema> | null = null

      for await (const event of llmStream) {
        // Check for cancellation during streaming
        if (handle.isCancelled()) {
          handle.emit({ type: 'cancelled', reason: 'User cancelled' })
          await db
            .update(practiceAttachments)
            .set({ parsingStatus: null, parsingError: null })
            .where(eq(practiceAttachments.id, attachmentId))
          return
        }

        // Handle domain-specific events (reasoning/output_delta handled by middleware)
        if (event.type === 'error') {
          handle.emit({
            type: 'problem_error',
            problemIndex,
            message: event.message,
            code: event.code,
          })
        } else if (event.type === 'complete') {
          problemResult = event.data
        }
        // reasoning and output_delta events are handled by middleware
      }

      if (problemResult) {
        reparsedProblems.push({
          index: problemIndex,
          originalProblem,
          newData: problemResult,
        })

        // Notify client this problem is done
        handle.emit({
          type: 'problem_complete',
          problemIndex,
          problemNumber: originalProblem.problemNumber,
          result: problemResult,
          currentIndex: i,
          totalProblems: problemIndices.length,
        })
      }
    } catch (err) {
      console.error(`[WorksheetReparseTask] Failed to re-parse problem ${problemIndex}:`, err)
      handle.emit({
        type: 'problem_error',
        problemIndex,
        message: err instanceof Error ? err.message : 'Unknown error',
      })
      // Continue with other problems
    }
  }

  // Final cancellation check
  if (handle.isCancelled()) {
    handle.emit({ type: 'cancelled', reason: 'User cancelled' })
    await db
      .update(practiceAttachments)
      .set({ parsingStatus: null, parsingError: null })
      .where(eq(practiceAttachments.id, attachmentId))
    return
  }

  handle.setProgress(90, 'Merging results...')

  // Merge results back into existing parsing result
  const adjustedBoxMap = new Map<number, BoundingBox>()
  for (let i = 0; i < problemIndices.length; i++) {
    adjustedBoxMap.set(problemIndices[i], boundingBoxes[i])
  }

  const updatedProblems = [...existingResult.problems]
  for (const { index, originalProblem, newData } of reparsedProblems) {
    const correctAnswer = newData.terms.reduce((a, b) => a + b, 0)
    const userAdjustedBox = adjustedBoxMap.get(index) ?? originalProblem.problemBoundingBox
    updatedProblems[index] = {
      ...originalProblem,
      terms: newData.terms,
      studentAnswer: newData.studentAnswer,
      correctAnswer,
      format: newData.format,
      termsConfidence: newData.termsConfidence,
      studentAnswerConfidence: newData.studentAnswerConfidence,
      problemBoundingBox: userAdjustedBox,
    }
  }

  // Update the parsing result
  const updatedResult: WorksheetParsingResult = {
    ...existingResult,
    problems: updatedProblems,
    overallConfidence:
      updatedProblems.reduce(
        (sum, p) => sum + Math.min(p.termsConfidence, p.studentAnswerConfidence),
        0
      ) / updatedProblems.length,
    needsReview: updatedProblems.some(
      (p) => Math.min(p.termsConfidence, p.studentAnswerConfidence) < 0.7
    ),
  }

  // Save updated result to database
  const status: ParsingStatus = updatedResult.needsReview ? 'needs_review' : 'approved'
  await db
    .update(practiceAttachments)
    .set({
      rawParsingResult: updatedResult,
      confidenceScore: updatedResult.overallConfidence,
      needsReview: updatedResult.needsReview,
      parsingStatus: status,
      parsingError: null,
    })
    .where(eq(practiceAttachments.id, attachmentId))

  handle.emit({
    type: 'reparse_complete',
    reparsedCount: reparsedProblems.length,
    reparsedIndices: reparsedProblems.map((p) => p.index),
    status,
  })

  handle.complete({
    reparsedCount: reparsedProblems.length,
    reparsedIndices: reparsedProblems.map((p) => p.index),
    updatedResult,
    status,
  })
}