All files / web/src/lib/tasks audio-generate.ts

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

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                                                                                                                                                                                                                                                                                                                                                                                                                 
import { existsSync, mkdirSync, unlinkSync, writeFileSync } from 'fs'
import { join } from 'path'
import { AUDIO_MANIFEST } from '@/lib/audio/audioManifest'
import { buildTtsParams } from '@/lib/audio/toneDirections'
import { createTask } from '../task-manager'
import { recordTtsUsage } from '@/lib/ai-usage/helpers'
import { AiFeature } from '@/lib/ai-usage/features'
import type { AudioGenerateEvent } from './events'

const AUDIO_DIR = join(process.cwd(), 'data', 'audio')

export interface AudioGenerateInput {
  voice: string
  clipIds?: string[] // If provided, delete these files first and regenerate only them
  _userId?: string
}

export interface AudioGenerateOutput {
  voice: string
  generated: number
  errors: number
  total: number
}

/**
 * Start an audio generation background task.
 *
 * Generates all missing TTS clips for a given voice using OpenAI TTS API.
 * Reports per-clip progress via task events.
 */
export async function startAudioGeneration(input: AudioGenerateInput): Promise<string> {
  return createTask<AudioGenerateInput, AudioGenerateOutput, AudioGenerateEvent>(
    'audio-generate',
    input,
    async (handle, config) => {
      const apiKey = process.env.LLM_OPENAI_API_KEY || process.env.OPENAI_API_KEY
      if (!apiKey) {
        handle.fail('LLM_OPENAI_API_KEY is not configured')
        return
      }

      const voiceDir = join(AUDIO_DIR, config.voice)
      mkdirSync(voiceDir, { recursive: true })

      // If clipIds provided, delete those files first so they'll be "missing"
      if (config.clipIds && config.clipIds.length > 0) {
        const targetSet = new Set(config.clipIds)
        for (const clip of AUDIO_MANIFEST) {
          if (targetSet.has(clip.id)) {
            const filePath = join(voiceDir, clip.filename)
            if (existsSync(filePath)) {
              unlinkSync(filePath)
            }
          }
        }
      }

      // Determine which clips to generate
      const clipScope = config.clipIds
        ? AUDIO_MANIFEST.filter((clip) => config.clipIds!.includes(clip.id))
        : AUDIO_MANIFEST

      const missing = clipScope.filter((clip) => !existsSync(join(voiceDir, clip.filename)))

      handle.emit({
        type: 'audio_started',
        voice: config.voice,
        totalClips: clipScope.length,
        missingClips: missing.length,
        clipIds: config.clipIds,
      })

      if (missing.length === 0) {
        handle.emit({
          type: 'audio_complete',
          generated: 0,
          errors: 0,
          total: clipScope.length,
        })
        handle.complete({
          voice: config.voice,
          generated: 0,
          errors: 0,
          total: clipScope.length,
        })
        return
      }

      handle.setProgress(0, `Generating 0/${missing.length} clips`)

      let generated = 0
      let errors = 0
      let consecutiveErrors = 0
      let lastErrorMessage = ''
      const MAX_CONSECUTIVE_ERRORS = 3

      for (let i = 0; i < missing.length; i++) {
        if (handle.isCancelled()) break

        const clip = missing[i]

        try {
          const response = await fetch('https://api.openai.com/v1/audio/speech', {
            method: 'POST',
            headers: {
              Authorization: `Bearer ${apiKey}`,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              model: 'gpt-4o-mini-tts',
              voice: config.voice,
              ...buildTtsParams(clip.text, clip.tone),
              response_format: 'mp3',
            }),
          })

          if (!response.ok) {
            const errText = await response.text()
            errors++
            const errorMsg = `HTTP ${response.status}: ${errText}`
            consecutiveErrors++
            lastErrorMessage = errorMsg
            handle.emit({
              type: 'clip_error',
              clipId: clip.id,
              error: errorMsg,
            })
          } else {
            const arrayBuffer = await response.arrayBuffer()
            writeFileSync(join(voiceDir, clip.filename), Buffer.from(arrayBuffer))
            generated++
            consecutiveErrors = 0
            handle.emit({ type: 'clip_done', clipId: clip.id })
            if (config._userId) {
              recordTtsUsage(clip.text, 'gpt-4o-mini-tts', {
                userId: config._userId,
                feature: AiFeature.TTS_BATCH,
                backgroundTaskId: handle.id,
              })
            }
          }
        } catch (err) {
          errors++
          const errorMsg = err instanceof Error ? err.message : String(err)
          consecutiveErrors++
          lastErrorMessage = errorMsg
          handle.emit({
            type: 'clip_error',
            clipId: clip.id,
            error: errorMsg,
          })
        }

        // Abort early on systemic failures
        if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
          const friendlyMsg = describeSystemicError(lastErrorMessage, config.voice)
          handle.fail(friendlyMsg)
          return
        }

        const progress = Math.round(((i + 1) / missing.length) * 100)
        handle.setProgress(progress, `Generating ${i + 1}/${missing.length} clips`)
      }

      handle.emit({
        type: 'audio_complete',
        generated,
        errors,
        total: clipScope.length,
      })

      handle.complete({
        voice: config.voice,
        generated,
        errors,
        total: clipScope.length,
      })
    }
  )
}

/** Map raw error messages to user-friendly descriptions for systemic failures. */
function describeSystemicError(rawError: string, voice: string): string {
  if (rawError.includes('EACCES') || rawError.includes('permission denied')) {
    return `Permission denied writing audio files for voice "${voice}". The server cannot write to the audio storage directory. An admin needs to fix the directory permissions.`
  }
  if (rawError.includes('ENOSPC') || rawError.includes('no space')) {
    return `Disk full — not enough space to write audio files for voice "${voice}".`
  }
  if (rawError.includes('ENOENT')) {
    return `Audio storage directory not found for voice "${voice}". The volume may not be mounted.`
  }
  if (rawError.includes('HTTP 401') || rawError.includes('HTTP 403')) {
    return `OpenAI API authentication failed. Check that LLM_OPENAI_API_KEY is valid.`
  }
  if (rawError.includes('HTTP 429')) {
    return `OpenAI API rate limit exceeded. Try again later or reduce batch size.`
  }
  return `Generation failed after repeated errors: ${rawError}`
}