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 | import { MATH_CONSTANTS, METAPHOR_PROMPT_PREFIX, MATH_PROMPT_PREFIX, THEME_MODIFIERS, } from '@/components/toys/number-line/constants/constantsData' import { createTask } from '../task-manager' import { getImageProvider } from '../image-providers' import { generateAndStoreImage } from '../image-generation' import { imageExists } from '../image-storage' import type { ImageGenerateEvent } from './events' import { recordImageGenUsage } from '../ai-usage/helpers' import { AiFeature } from '../ai-usage/features' export { IMAGE_PROVIDERS } from '../image-providers' export interface ImageGenerateInput { provider: 'gemini' | 'openai' model: string targets: Array<{ constantId: string; style: 'metaphor' | 'math'; theme?: 'light' | 'dark' }> forceRegenerate?: boolean _userId?: string } export interface ImageGenerateOutput { generated: number skipped: number failed: number results: Array<{ constantId: string style: string status: 'generated' | 'skipped' | 'failed' error?: string }> } /** * Start an image generation background task. * * Generates constant illustrations using the specified AI provider. * Reports per-image progress via task events. */ export async function startImageGeneration(input: ImageGenerateInput): Promise<string> { return createTask<ImageGenerateInput, ImageGenerateOutput, ImageGenerateEvent>( 'image-generate', input, async (handle, config) => { const provider = getImageProvider(config.provider) if (!provider) { handle.fail(`Unknown image provider: ${config.provider}`) return } if (!provider.isAvailable()) { const { envKey, envKeyAlt } = provider.meta const keys = envKeyAlt ? `${envKey} or ${envKeyAlt}` : envKey handle.fail( `No API key configured for ${provider.meta.name}. Set ${keys} in your environment.` ) return } // Build lookup for constant data const constantMap = new Map(MATH_CONSTANTS.map((c) => [c.id, c])) // Determine work items const results: ImageGenerateOutput['results'] = [] let generated = 0 let skipped = 0 let failed = 0 let consecutiveErrors = 0 const MAX_CONSECUTIVE_ERRORS = 3 const total = config.targets.length handle.setProgress(0, `Starting generation of ${total} images`) for (let i = 0; i < config.targets.length; i++) { if (handle.isCancelled()) break const target = config.targets[i] const constant = constantMap.get(target.constantId) if (!constant) { results.push({ constantId: target.constantId, style: target.style, status: 'failed', error: `Unknown constant: ${target.constantId}`, }) failed++ continue } const filename = `${target.constantId}-${target.style}${target.theme ? `-${target.theme}` : ''}.png` const storageTarget = { type: 'static' as const, relativePath: `images/constants/${filename}`, } // Skip if already exists and not force-regenerating if (!config.forceRegenerate && imageExists(storageTarget)) { results.push({ constantId: target.constantId, style: target.style, status: 'skipped', }) skipped++ const progress = Math.round(((i + 1) / total) * 100) handle.setProgress( progress, `Skipped ${target.constantId} ${target.style} (already exists)` ) continue } handle.emit({ type: 'image_started', constantId: target.constantId, style: target.style, model: config.model, provider: config.provider, ...(target.theme && { theme: target.theme }), }) handle.emit({ type: 'batch_progress', completed: generated + skipped + failed, total, currentConstant: constant.name, currentStyle: target.style, ...(target.theme && { theme: target.theme }), }) // Build the full prompt const prefix = target.style === 'metaphor' ? METAPHOR_PROMPT_PREFIX : MATH_PROMPT_PREFIX const suffix = target.style === 'metaphor' ? constant.metaphorPrompt : constant.mathPrompt const themeModifier = target.theme ? ` ${THEME_MODIFIERS[target.theme][target.style]}` : '' const fullPrompt = `${prefix} ${suffix}${themeModifier}` try { const result = await generateAndStoreImage({ provider: config.provider, model: config.model, prompt: fullPrompt, storageTarget, }) const sizeBytes = result.sizeBytes ?? 0 generated++ consecutiveErrors = 0 if (config._userId) { recordImageGenUsage(config.provider, config.model, { userId: config._userId, feature: AiFeature.IMAGE_CONSTANT, backgroundTaskId: handle.id, }) } handle.emit({ type: 'image_complete', constantId: target.constantId, style: target.style, filePath: result.publicUrl, sizeBytes, ...(target.theme && { theme: target.theme }), }) results.push({ constantId: target.constantId, style: target.style, status: 'generated', }) } catch (err) { failed++ consecutiveErrors++ const errorMsg = err instanceof Error ? err.message : String(err) handle.emit({ type: 'image_error', constantId: target.constantId, style: target.style, error: errorMsg, ...(target.theme && { theme: target.theme }), }) results.push({ constantId: target.constantId, style: target.style, status: 'failed', error: errorMsg, }) if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) { handle.fail( `Generation aborted after ${MAX_CONSECUTIVE_ERRORS} consecutive failures: ${errorMsg}` ) return } } const progress = Math.round(((i + 1) / total) * 100) handle.setProgress( progress, `${generated + skipped + failed}/${total} — ${generated} generated, ${skipped} skipped, ${failed} failed` ) } handle.emit({ type: 'batch_complete', generated, skipped, failed, }) handle.complete({ generated, skipped, failed, results }) } ) } |